package com.easyn.P2PCam264;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StatFs;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.easyn.CamLinePro.MultiViewActivity;
import com.easyn.CamLinePro.R;
import com.easyn.command.AVIOCTRLDEFs;
import com.easyn.command.AVIOCTRLDEFs.SMsgAVIoctrlGetSupportStreamReq;
import com.easyn.command.AVIOCTRLDEFs.SStreamDef;
import com.tutk.IOTC.AVFrame;
import com.tutk.IOTC.Camera;
import com.tutk.IOTC.CameraListener;
import com.tutk.IOTC.IMonitor;
import com.tutk.IOTC.IOTCAPIs;
import com.tutk.IOTC.IRegisterIOTCListener;
import com.tutk.IOTC.MediaCodecListener;
import com.tutk.IOTC.MediaCodecMonitor;
import com.tutk.IOTC.MonitorClickListener;
import com.tutk.IOTC.St_SInfo;
import com.tutk.Logger.Glog;

public class LiveViewActivity extends SherlockActivity implements
		ViewSwitcher.ViewFactory, IRegisterIOTCListener, MonitorClickListener,
		android.view.View.OnTouchListener, CameraListener, MediaCodecListener,
		OnClickListener {

	private static final int BUILD_VERSION_CODES_ICE_CREAM_SANDWICH = 14;
	private static final int STS_CHANGE_CHANNEL_STREAMINFO = 99;
	private static final int STS_SNAPSHOT_SCANED = 98;
	// private static final String FILE_TYPE = "image/*";
	private int mPreBrightness_Level = -1; // 上一个设置
	private int mPreContrast_Level = -1; // 上一个设置
	private static final int REQUEST_CODE_ALBUM = 99;
	private VerticalSeekBar mVerSeekBar_Brightness;
	private VerticalSeekBar seekbar_Contrast;
	private static final int OPT_MENU_ITEM_ALBUM = Menu.FIRST;
	private static final int OPT_MENU_ITEM_SNAPSHOT = Menu.FIRST + 1;
	private static final int OPT_MENU_ITEM_AUDIOCTRL = Menu.FIRST + 4;
	private static final int OPT_MENU_ITEM_AUDIO_IN = Menu.FIRST + 5;
	private static final int OPT_MENU_ITEM_AUDIO_OUT = Menu.FIRST + 6;
	private Button infrared_open, infrared_close, infrared_auto;
	private final int THUMBNAIL_LIMIT_HEIGHT = 720;
	private final int THUMBNAIL_LIMIT_WIDTH = 1280;
	private boolean canSetBrightness = false;
	private boolean canSetContrast = false;
	private IMonitor monitor = null;
	private MyCamera mCamera = null;
	private DeviceInfo mDevice = null;
	private int EnvironmentMode = 0;
	// private int SOPTZOOM=-1;
	private ImageButton btn_infrared;
	private int mMonitorIndex = -1;
	private int OriginallyChannelIndex = -1;
	private int mBrightness_Level = 0;
	private int mContrast_Level = 0;
	private TextView txt_title;
	private String mDevUID;
	private String mDevUUID;
	private String mConnStatus = "";
	private String mFilePath = "";
	private int mVideoFPS;
	private long mVideoBPS;
	private int mOnlineNm;
	private int mFrameCount;
	private int mIncompleteFrameCount;
	private int mVideoWidth;
	private int mVideoHeight;
	private int mMiniVideoWidth;
	private int mMiniVideoHeight;
	private int mSelectedChannel;
	private ImageButton btn_restore;
	private RelativeLayout toolbar_layout;
	private RelativeLayout toolbar_layout2;
	private RelativeLayout toolbar_layout3;
	private RelativeLayout toolbar_layout_head;
	private RelativeLayout linSpeaker;
	private LinearLayout linPnlCameraInfo;
	private RelativeLayout linQVGA;
	private RelativeLayout linPnlemode;
	private RelativeLayout infrared_layout;
	private LinearLayout nullLayout;
	private VerticalScrollView myScrollView;
	private HorizontalScrollView myHorScrollView;

	private boolean LevelFlip = false;
	private boolean VerticalFlip = false;
	private boolean isOpenLinQVGA = false;
	private boolean isOpenLinEmode = false;
	private boolean isOpenInfrared = false;
	private boolean isShowToolBar = true;

	// TOOLBAR
	private HorizontalScrollView toolbarScrollView = null;
	private ImageButton button_toolbar_speaker;
	private ImageButton button_toolbar_recording;
	private ImageButton button_toolbar_snapshot;
	private ImageButton button_toolbar_mirror;
	private ImageButton button_toolbar_mirror_rl;
	private ImageButton button_toolbar_SET;
	private ImageButton button_toolbar_QVGA;
	private ImageButton button_toolbar_EMODE;
	private LinearLayout layoutfc;
	private ImageButton button_toolbar_presetting;
	private ImageButton button_toolbar_cruise;
	private TextView pre_text;
	private ImageButton btn_pre1, btn_cru1, btn_cru2, btn_cru3;
	private ImageButton btn_pre2;
	private ImageButton btn_pre3;
	private ImageButton btn_pre4;
	private boolean mPreBtnLongPress = false;

	private ImageButton btn_speaker;

	private TextView txtConnectionSlash;
	private TextView txtResolutionSlash;
	private TextView txtShowFPS;
	private TextView txtFPSSlash;
	private TextView txtShowBPS;
	private TextView txtShowOnlineNumber;
	private TextView txtOnlineNumberSlash;
	private TextView txtShowFrameRatio;
	private TextView txtFrameCountSlash;
	private TextView txtQuality;
	private TextView txtRecvFrmPreSec;
	private TextView txtRecvFrmSlash;
	private TextView txtDispFrmPreSeco;

	private TextView txtConnectionStatus;
	private TextView txtConnectionMode;
	private TextView txtResolution;
	private TextView txtFrameRate;
	private TextView txtBitRate;
	private TextView txtOnlineNumber;
	private TextView txtFrameCount;
	private TextView txtIncompleteFrameCount;
	private TextView txtPerformance;
	private TextView mCHTextView;

	private boolean mIsListening = false;
	private boolean mIsSpeaking = false;
	private boolean mIsRecording = false;

	private BitmapDrawable bg;
	private BitmapDrawable bgSplit;

	private ImageButton CH_button;

	private Button qvga_button1;
	private Button qvga_button2;
	private Button qvga_button3;
	private Button qvga_button4;
	private Button qvga_button5;
	private Button emode_button1;
	private Button emode_button2;
	private Button emode_button3;
	private Button emode_button4;

	private ImageButton btn_zoom_add;
	private ImageButton btn_zoom_sub;

	private Context mContext;
	private static String filename;
	private boolean unavailable = false;

	private static boolean wait_receive = true;
	private static boolean Watch_album = false;

	private final boolean m_RunSoftDecode = true;
	private final boolean m_RunSoftDecode2 = true;

	// private AlertDialog.Builder mbuilder = null;
	// private Dialog mdlg = null;

	private enum EMZoomAction {
		zoom_in, zoom_out
	};

	private EMZoomAction ZoomAction = EMZoomAction.zoom_in;
	private final int mZoomOperDelayIn = 1000;// 发送命令间隔时间
	private final int mZoomOperDelayOut = 1000;// 发送命令间隔时间
	private BrightnessOnSeekBarChangeListener br;
	private ContrastOnSeekBarChangeListener cr;

	private void setQulityButtonColor(boolean bSet, int index) {
		if (!bSet)
			index = DatabaseManager.VideoQuality(mCamera.getUID(), 0);

		qvga_button1.setTextColor(Color.BLUE);
		qvga_button2.setTextColor(Color.BLUE);
		qvga_button3.setTextColor(Color.BLUE);
		qvga_button4.setTextColor(Color.BLUE);
		qvga_button5.setTextColor(Color.BLUE);

		switch (index) {
		case 1:
			if (!bSet)
				qvga_button1.setTextColor(Color.RED);
			else
				qvga_button1.setTextColor(Color.BLUE);
			break;
		case 2:
			if (!bSet)
				qvga_button2.setTextColor(Color.RED);
			else
				qvga_button2.setTextColor(Color.BLUE);
			break;
		case 3:
			if (!bSet)
				qvga_button3.setTextColor(Color.RED);
			else
				qvga_button3.setTextColor(Color.BLUE);
			break;
		case 4:
			if (!bSet)
				qvga_button4.setTextColor(Color.RED);
			else
				qvga_button4.setTextColor(Color.BLUE);
			break;
		case 5:
			if (!bSet)
				qvga_button5.setTextColor(Color.RED);
			else
				qvga_button5.setTextColor(Color.BLUE);
			break;
		}
	}

	private void setEMode(int mode) {
		if (emode_button1 == null) {
			return;
		}
		emode_button1.setTextColor(Color.BLUE);
		emode_button2.setTextColor(Color.BLUE);
		if (mode == 0)
			emode_button1.setTextColor(Color.RED);
		else if (mode == 1)
			emode_button2.setTextColor(Color.RED);
	}

	private void setInfrared(int mode) {
		// if (infrared_open == null) {
		// return;
		// }
		// emode_button1.setTextColor(Color.BLUE);
		// emode_button2.setTextColor(Color.BLUE);
		// if (mode == 0)
		// emode_button1.setTextColor(Color.RED);
		// else if (mode == 1)
		// emode_button2.setTextColor(Color.RED);
	}

	private void RecordHideOther(boolean bHide) {
		/*
		 * int hide = View.INVISIBLE; if (!bHide) hide = View.VISIBLE; if
		 * (button_toolbar_speaker != null)
		 * button_toolbar_speaker.setVisibility(hide); if
		 * (button_toolbar_snapshot != null)
		 * button_toolbar_snapshot.setVisibility(hide);
		 * 
		 * if (button_toolbar_mirror != null)
		 * button_toolbar_mirror.setVisibility(hide); if
		 * (button_toolbar_mirror_rl != null)
		 * button_toolbar_mirror_rl.setVisibility(hide); if (button_toolbar_SET
		 * != null) button_toolbar_SET.setVisibility(hide); if
		 * (button_toolbar_QVGA != null)
		 * button_toolbar_QVGA.setVisibility(hide); if (button_toolbar_EMODE !=
		 * null) button_toolbar_EMODE.setVisibility(hide); if (btn_zoom_add !=
		 * null) btn_zoom_add.setVisibility(hide); if (btn_zoom_sub != null)
		 * btn_zoom_sub.setVisibility(hide);
		 * 
		 * if (toolbarScrollView != null) toolbarScrollView.setVisibility(hide);
		 */

	}

	@SuppressWarnings("deprecation")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		setContentView(R.layout.live_view_portrait);
		br = new BrightnessOnSeekBarChangeListener();
		cr = new ContrastOnSeekBarChangeListener();
		bg = (BitmapDrawable) getResources().getDrawable(R.drawable.bg_striped);
		bgSplit = (BitmapDrawable) getResources().getDrawable(
				R.drawable.bg_striped_split_img);

		Bundle bundle = this.getIntent().getExtras();
		mDevUID = bundle.getString("dev_uid");
		mDevUUID = bundle.getString("dev_uuid");
		mConnStatus = bundle.getString("conn_status");
		mSelectedChannel = bundle.getInt("camera_channel");
		OriginallyChannelIndex = bundle.getInt("camera_channel");
		mMonitorIndex = bundle.getInt("MonitorIndex");

		for (MyCamera camera : MultiViewActivity.CameraList) {
			if (mDevUID.equalsIgnoreCase(camera.getUID())
					&& mDevUUID.equalsIgnoreCase(camera.getUUID())) {
				mCamera = camera;
				break;
			}
		}

		for (DeviceInfo dev : MultiViewActivity.DeviceList) {
			if (mDevUID.equalsIgnoreCase(dev.UID)
					&& mDevUUID.equalsIgnoreCase(dev.UUID)) {
				mDevice = dev;
				break;
			}
		}

		// Configuration cfg = getResources().getConfiguration();
		//
		// if (cfg.orientation == Configuration.ORIENTATION_PORTRAIT) {
		// setupViewInPortraitLayout();
		// } else if (cfg.orientation == Configuration.ORIENTATION_LANDSCAPE) {
		// setupViewInLandscapeLayout();
		// }

		if (mCamera != null) {

			mCamera.registerIOTCListener(this);
			mCamera.SetCameraListener(this);

			if (!mCamera.isSessionConnected()) {

				mCamera.connect(mDevUID);
				mCamera.start(Camera.DEFAULT_AV_CHANNEL, mDevice.View_Account,
						mDevice.View_Password);
				mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
						AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GETSUPPORTSTREAM_REQ,
						SMsgAVIoctrlGetSupportStreamReq.parseContent());
				mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
						AVIOCTRLDEFs.IOTYPE_USER_IPCAM_DEVINFO_REQ,
						AVIOCTRLDEFs.SMsgAVIoctrlDeviceInfoReq.parseContent());
				mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
						AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GETAUDIOOUTFORMAT_REQ,
						AVIOCTRLDEFs.SMsgAVIoctrlGetAudioOutFormatReq
								.parseContent());
				mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
						AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GET_TIMEZONE_REQ,
						AVIOCTRLDEFs.SMsgAVIoctrlTimeZone.parseContent());
			}

			mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
					AVIOCTRLDEFs.IOTYPE_USER_IPCAM_SETSTREAMCTRL_REQ,
					AVIOCTRLDEFs.SMsgAVIoctrlSetStreamCtrlReq.parseContent(
							mDevice.ChannelIndex,
							(byte) DatabaseManager.VideoQuality(
									mCamera.getUID(), 0)));

			mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
					AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GET_ENVIRONMENT_REQ,
					AVIOCTRLDEFs.SMsgAVIoctrlGetEnvironmentReq
							.parseContent(mDevice.ChannelIndex));
			mCamera.startShow(mSelectedChannel, true, m_RunSoftDecode,
					m_RunSoftDecode2);

			/*
			 * if (mCamera.LastAudioMode == 1) {
			 * mCamera.startListening(mSelectedChannel); mIsListening = true; }
			 * if (mCamera.LastAudioMode == 2) {
			 * mCamera.startSpeaking(mSelectedChannel); mIsSpeaking = true; }
			 */
		}

		// Inflate the custom view
		final View audioView = LayoutInflater.from(this).inflate(
				R.layout.two_way_audio, null);

		// Bind to its state change
		((RadioGroup) audioView.findViewById(R.id.radioAudio))
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {
					@Override
					public void onCheckedChanged(RadioGroup group, int checkedId) {

						if (checkedId == audioView.findViewById(
								R.id.radioSpeaker).getId()) {

							if (mCamera.isChannelConnected(mSelectedChannel)) {
								mCamera.stopSpeaking(mSelectedChannel);
								mCamera.startListening(mSelectedChannel,
										mIsRecording);
								mIsListening = true;
								mIsSpeaking = false;
							}

						} else if (checkedId == audioView.findViewById(
								R.id.radioMicrophone).getId()) {

							if (mCamera.isChannelConnected(mSelectedChannel)) {
								mCamera.stopListening(mSelectedChannel);
								mCamera.startSpeaking(mSelectedChannel);
								mIsListening = false;
								mIsSpeaking = true;
							}
						}
					}
				});

		// getSupportActionBar().setCustomView(audioView);
		// getSupportActionBar().setDisplayShowCustomEnabled(true);

		/*
		 * mbuilder = new AlertDialog.Builder(new ContextThemeWrapper(this,
		 * R.style.AlertDialogCustom)); mdlg = mbuilder.create(); LayoutInflater
		 * inflater = mdlg.getLayoutInflater(); View view =
		 * inflater.inflate(R.layout.videowait, null); mdlg.setView(view, 0, 0,
		 * 0, 0);
		 */// dlg.setCanceledOnTouchOutside(false);
			// dlg.setCancelable(false);

		/*
		 * mdlg = new Dialog(this, R.style.FullScreenDialog); LayoutInflater
		 * mLayoutInflater =
		 * (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		 * View reNameView = mLayoutInflater.inflate(R.layout.videowait, null);
		 * LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
		 * LayoutParams.WRAP_CONTENT); mdlg.addContentView(reNameView, params);
		 */

		// mdlg.setCanceledOnTouchOutside(false);
		// mdlg.setCancelable(false);
	}

	@Override
	protected void onStart() {
		super.onStart();
		// FlurryAgent.onStartSession(this, "Q1SDXDZQ21BQMVUVJ16W");
	}

	@Override
	protected void onStop() {
		handler.removeCallbacks(zoom_runable);
		super.onStop();
		// FlurryAgent.onEndSession(this);
	}

	@Override
	protected void onPause() {
		super.onPause();

		if (mCamera != null) {
			mCamera.unregisterIOTCListener(this);
			mCamera.stopSpeaking(mSelectedChannel);
			mCamera.stopListening(mSelectedChannel);
			mCamera.stopShow(mSelectedChannel);
		}
		if (mIsRecording) {
			// mIsSpeaking = false;
			// mIsListening = false;
			mCamera.stopRecording();
			button_toolbar_recording
					.setBackgroundResource(R.drawable.btn_recording_switch_start);
			mIsRecording = false;
		}

		if (monitor != null)
			monitor.deattachCamera();
	}

	@Override
	protected void onResume() {
		super.onResume();

		if (monitor != null) {
			monitor.enableDither(mCamera.mEnableDither);
			monitor.attachCamera(mCamera, mSelectedChannel);
		}

		if (mCamera != null) {
			mCamera.registerIOTCListener(this);

			mCamera.startShow(mSelectedChannel, true, m_RunSoftDecode,
					m_RunSoftDecode2);

			if (mIsListening)
				mCamera.startListening(mSelectedChannel, mIsRecording);
			if (mIsSpeaking)
				mCamera.startSpeaking(mSelectedChannel);
		}

		Configuration cfg = getResources().getConfiguration();

		if (cfg.orientation == Configuration.ORIENTATION_PORTRAIT) {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					setupViewInPortraitLayout();
				}
			});
		} else if (cfg.orientation == Configuration.ORIENTATION_LANDSCAPE) {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					setupViewInLandscapeLayout();
				}
			});
		}
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);

		Configuration cfg = getResources().getConfiguration();

		if (cfg.orientation == Configuration.ORIENTATION_LANDSCAPE) {
			if (unavailable)
				setupViewInLandscapeLayout_wait();
			else
				setupViewInLandscapeLayout();

		} else if (cfg.orientation == Configuration.ORIENTATION_PORTRAIT) {
			if (unavailable)
				setupViewInPortraitLayout_wait();
			else
				setupViewInPortraitLayout();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == REQUEST_CODE_ALBUM) {
			monitor = (IMonitor) findViewById(R.id.monitor);
			monitor.setMaxZoom(3.0f);
			monitor.enableDither(mCamera.mEnableDither);
			monitor.attachCamera(mCamera, mSelectedChannel);
		}

		else if (requestCode == MultiViewActivity.REQUEST_CODE_CAMERA_EDIT) {

			// txt_title.setText(mDevice.NickName);
			switch (resultCode) {
			case MultiViewActivity.REQUEST_CODE_CAMERA_EDIT_DELETE_OK:
				Bundle extras = data.getExtras();
				Intent Intent = new Intent();
				Intent.putExtras(extras);
				setResult(MultiViewActivity.REQUEST_CODE_CAMERA_EDIT_DELETE_OK,
						Intent);
				finish();

				break;
			}
		}
	}

	private OnLongClickListener longClick = new OnLongClickListener() {

		@Override
		public boolean onLongClick(View v) {
			TextView tv_reminder = (TextView) findViewById(R.id.tv_reminder);
			tv_reminder.setText(getString(R.string.Pre_saveok));
			btn_pre1.setOnTouchListener(LiveViewActivity.this);
			btn_pre2.setOnTouchListener(LiveViewActivity.this);
			btn_pre3.setOnTouchListener(LiveViewActivity.this);
			btn_pre4.setOnTouchListener(LiveViewActivity.this);
			switch (v.getId()) {
			case R.id.btn_pre1:
				mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
						HICHIPIOCTRDEFs.IOTYPE_USER_IPCAM_SETPRESET_REQ,
						HICHIPIOCTRDEFs.SMsgAVIoctrlSetPresetReq.parseContent(
								Camera.DEFAULT_AV_CHANNEL, 1));

				break;
			case R.id.btn_pre2:
				mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
						HICHIPIOCTRDEFs.IOTYPE_USER_IPCAM_SETPRESET_REQ,
						HICHIPIOCTRDEFs.SMsgAVIoctrlSetPresetReq.parseContent(
								Camera.DEFAULT_AV_CHANNEL, 2));
				break;
			case R.id.btn_pre3:
				mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
						HICHIPIOCTRDEFs.IOTYPE_USER_IPCAM_SETPRESET_REQ,
						HICHIPIOCTRDEFs.SMsgAVIoctrlSetPresetReq.parseContent(
								Camera.DEFAULT_AV_CHANNEL, 3));
				break;
			case R.id.btn_pre4:
				mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
						HICHIPIOCTRDEFs.IOTYPE_USER_IPCAM_SETPRESET_REQ,
						HICHIPIOCTRDEFs.SMsgAVIoctrlSetPresetReq.parseContent(
								Camera.DEFAULT_AV_CHANNEL, 4));
				break;
			default:
				break;
			}
			return true;
		}
	};
	OnTouchListener addOntouch = new OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				SetPTZ((byte) 23);
				// btn_zoom_add.setBackgroundResource(R.drawable.leo_add_clicked);
				// mCamera.sendIOCtrl(mSelectedChannel,
				// AVIOCTRLDEFs.IOTYPE_USER_IPCAM_PTZ_COMMAND,
				// SMsgAVIoctrlPtzCmd.parseContent(
				// (byte)AVIOCTRLDEFs.AVIOCTRL_LENS_ZOOM_IN, (byte)10, (byte)0,
				// (byte)0, (byte)0,
				// (byte)mSelectedChannel, CONTINUOUS_MODE));
				// //CONTINUOUS_MODE=10; 内部是：result[7]=CONTINUOUS_MODE
				// ZoomAction = EMZoomAction.zoom_in;
				// handler.postDelayed(zoom_runable, 500);
				break;
			case MotionEvent.ACTION_UP:
				// btn_zoom_add.setBackgroundResource(R.drawable.leo_add);
				// handler.removeCallbacks(zoom_runable);
				SetPTZ((byte) 0);
				break;
			default:
				break;
			}
			return false;
		}
	};
	OnTouchListener subOntouch = new OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				// btn_zoom_sub.setBackgroundResource(R.drawable.leo_sub_clicked);
				// ZoomAction = EMZoomAction.zoom_out;
				// handler.postDelayed(zoom_runable, 500);
				SetPTZ((byte) 24);
				break;
			case MotionEvent.ACTION_UP:
				// btn_zoom_sub.setBackgroundResource(R.drawable.leo_sub);
				SetPTZ((byte) 0);
				// handler.removeCallbacks(zoom_runable);
				break;
			default:
				break;
			}
			return false;
		}
	};
	private ImageButton button_brightness;
	private ImageButton button_contrast;

	private void setupViewInLandscapeLayout() {
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getWindow().clearFlags(
				WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
		ActionBar actionBar = getActionBar();
		actionBar.hide();
		setContentView(R.layout.live_view_landscape);
		mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
				AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GET_IMAGE_PARAM_REQ,
				com.tutk.IOTC.AVIOCTRLDEFs.SMsgAVIoctrlGetBrightReq
						.parseContent(Camera.DEFAULT_AV_CHANNEL));
		// toolbarScrollView = (HorizontalScrollView)
		// findViewById(R.id.ScrollView_toolbar);
		// if (toolbarScrollView != null)
		// toolbarScrollView.setHorizontalFadingEdgeEnabled(false);
		// toolbar_layout_head = (RelativeLayout)
		// findViewById(R.id.toolbar_layout_head);

		toolbar_layout = (RelativeLayout) findViewById(R.id.toolbar_layout);

		toolbar_layout.setVisibility(View.GONE);

		isShowToolBar = false;

		if (Build.VERSION.SDK_INT < BUILD_VERSION_CODES_ICE_CREAM_SANDWICH) {

			bg.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
			getSupportActionBar().setBackgroundDrawable(bg);

			bgSplit.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
			getSupportActionBar().setSplitBackgroundDrawable(bgSplit);
		}
		btn_restore = (ImageButton) findViewById(R.id.btn_restore);
		btn_infrared = (ImageButton) findViewById(R.id.btn_infrared);
		infrared_open = (Button) findViewById(R.id.infrared_open);
		infrared_open.setOnClickListener(InfraredClick);
		infrared_close = (Button) findViewById(R.id.infrared_close);
		infrared_close.setOnClickListener(InfraredClick);
		infrared_auto = (Button) findViewById(R.id.infrared_auto);
		infrared_auto.setOnClickListener(InfraredClick);
		button_brightness = (ImageButton) findViewById(R.id.button_brightness);
		button_contrast = (ImageButton) findViewById(R.id.button_contrast);
		button_brightness.setOnClickListener(this);
		button_contrast.setOnClickListener(this);
		mVerSeekBar_Brightness = (VerticalSeekBar) findViewById(R.id.seekbar_Brightness);
		mVerSeekBar_Brightness.setOnSeekBarChangeListener(br);
		seekbar_Contrast = (VerticalSeekBar) findViewById(R.id.seekbar_Contrast);
		seekbar_Contrast.setOnSeekBarChangeListener(cr);
		infrared_layout = (RelativeLayout) findViewById(R.id.infrared_layout);
		infrared_layout.setVisibility(View.GONE);

		if (isOpenInfrared) {
			btn_infrared.setBackgroundResource(R.drawable.infrared_click);
			infrared_layout.setVisibility(View.VISIBLE);
		}

		if (mCamera != null && mCamera.getMultiStreamSupported(0)
				&& mCamera.getSupportedStream().length > 1)
			getSupportActionBar().setSubtitle(
					getText(R.string.dialog_LiveView).toString() + " : "
							+ mDevice.NickName + " - CH"
							+ (mSelectedChannel + 1));
		else
			getSupportActionBar().setSubtitle(
					getText(R.string.dialog_LiveView).toString() + " : "
							+ mDevice.NickName);

		wait_receive = true;

	}

	private void setupViewInPortraitLayout() {

		getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getWindow().clearFlags(
				WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);

		ActionBar actionBar = getActionBar();
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
		actionBar.setCustomView(R.layout.titlebar);
		actionBar.show();

		setContentView(R.layout.advanced_settings);
		txt_title = (TextView) this.findViewById(R.id.bar_text);
		txt_title.setText(mDevice.NickName);

		setContentView(R.layout.live_view_portrait);

		toolbarScrollView = (HorizontalScrollView) findViewById(R.id.ScrollView_toolbar);
		if (toolbarScrollView != null)
			toolbarScrollView.setHorizontalFadingEdgeEnabled(false);
		toolbar_layout_head = null;

		nullLayout = (LinearLayout) findViewById(R.id.null_layout);

		linPnlCameraInfo = (LinearLayout) findViewById(R.id.pnlCameraInfo);

		linQVGA = (RelativeLayout) findViewById(R.id.qvga_layout);
		linQVGA.setVisibility(View.GONE);
		linSpeaker = (RelativeLayout) findViewById(R.id.speaker_layout);
		linSpeaker.setVisibility(View.GONE);
		linPnlemode = (RelativeLayout) findViewById(R.id.emode_layout);
		linPnlemode.setVisibility(View.GONE);

		// toolbar
		button_toolbar_speaker = (ImageButton) findViewById(R.id.button_speaker);
		button_toolbar_recording = (ImageButton) findViewById(R.id.button_recording);
		button_toolbar_snapshot = (ImageButton) findViewById(R.id.button_snapshot);
		button_toolbar_mirror = (ImageButton) findViewById(R.id.button_mirror);
		button_toolbar_mirror_rl = (ImageButton) findViewById(R.id.button_mirror_rl);
		button_toolbar_SET = (ImageButton) findViewById(R.id.button_SET);
		button_toolbar_QVGA = (ImageButton) findViewById(R.id.button_QVGA);
		button_toolbar_EMODE = (ImageButton) findViewById(R.id.button_EMODE);
		button_toolbar_presetting = (ImageButton) findViewById(R.id.button_presetting);
		button_toolbar_presetting.setOnClickListener(ToolBarClick);
		button_toolbar_cruise = (ImageButton) findViewById(R.id.button_cruise);
		button_toolbar_cruise.setOnClickListener(ToolBarClick);
		btn_cru1 = (ImageButton) findViewById(R.id.btn_cruise1);
		btn_cru2 = (ImageButton) findViewById(R.id.btn_cruise2);
		btn_cru3 = (ImageButton) findViewById(R.id.btn_cruise3);
		btn_cru1.setOnClickListener(CruiseClick);
		btn_cru2.setOnClickListener(CruiseClick);
		btn_cru3.setOnClickListener(CruiseClick);
		btn_pre1 = (ImageButton) findViewById(R.id.btn_pre1);
		btn_pre2 = (ImageButton) findViewById(R.id.btn_pre2);
		btn_pre3 = (ImageButton) findViewById(R.id.btn_pre3);
		btn_pre4 = (ImageButton) findViewById(R.id.btn_pre4);
		btn_pre1.setOnClickListener(PreClick);
		btn_pre2.setOnClickListener(PreClick);
		btn_pre3.setOnClickListener(PreClick);
		btn_pre4.setOnClickListener(PreClick);
		btn_pre1.setOnLongClickListener(longClick);
		btn_pre2.setOnLongClickListener(longClick);
		btn_pre3.setOnLongClickListener(longClick);
		btn_pre4.setOnLongClickListener(longClick);
		toolbar_layout = (RelativeLayout) findViewById(R.id.toolbar_layout);
		toolbar_layout2 = (RelativeLayout) findViewById(R.id.toolbar_layout2);
		toolbar_layout3 = (RelativeLayout) findViewById(R.id.toolbar_layout3);
		qvga_button1 = (Button) findViewById(R.id.qvga_button1);
		qvga_button2 = (Button) findViewById(R.id.qvga_button2);
		qvga_button3 = (Button) findViewById(R.id.qvga_button3);
		qvga_button4 = (Button) findViewById(R.id.qvga_button4);
		qvga_button5 = (Button) findViewById(R.id.qvga_button5);
		setQulityButtonColor(false, 0);
		btn_zoom_add = (ImageButton) findViewById(R.id.btn_zoom_add);
		btn_zoom_sub = (ImageButton) findViewById(R.id.btn_zoom_sub);

		btn_zoom_add.setOnTouchListener(addOntouch);

		btn_zoom_sub.setOnTouchListener(subOntouch);

		emode_button1 = (Button) findViewById(R.id.emode_button1);
		emode_button2 = (Button) findViewById(R.id.emode_button2);
		emode_button3 = (Button) findViewById(R.id.emode_button3);
		emode_button4 = (Button) findViewById(R.id.emode_button4);
		setEMode(EnvironmentMode);

		txtConnectionSlash = (TextView) findViewById(R.id.txtConnectionSlash);
		txtResolutionSlash = (TextView) findViewById(R.id.txtResolutionSlash);
		txtShowFPS = (TextView) findViewById(R.id.txtShowFPS);
		txtFPSSlash = (TextView) findViewById(R.id.txtFPSSlash);
		txtShowBPS = (TextView) findViewById(R.id.txtShowBPS);
		txtShowOnlineNumber = (TextView) findViewById(R.id.txtShowOnlineNumber);
		txtOnlineNumberSlash = (TextView) findViewById(R.id.txtOnlineNumberSlash);
		txtShowFrameRatio = (TextView) findViewById(R.id.txtShowFrameRatio);
		txtFrameCountSlash = (TextView) findViewById(R.id.txtFrameCountSlash);
		txtQuality = (TextView) findViewById(R.id.txtQuality);
		txtDispFrmPreSeco = (TextView) findViewById(R.id.txtDispFrmPreSeco);
		txtRecvFrmSlash = (TextView) findViewById(R.id.txtRecvFrmSlash);
		txtRecvFrmPreSec = (TextView) findViewById(R.id.txtRecvFrmPreSec);
		txtPerformance = (TextView) findViewById(R.id.txtPerformance);

		txtConnectionStatus = (TextView) findViewById(R.id.txtConnectionStatus);
		txtConnectionMode = (TextView) findViewById(R.id.txtConnectionMode);
		txtResolution = (TextView) findViewById(R.id.txtResolution);
		txtFrameRate = (TextView) findViewById(R.id.txtFrameRate);
		txtBitRate = (TextView) findViewById(R.id.txtBitRate);
		txtOnlineNumber = (TextView) findViewById(R.id.txtOnlineNumber);
		txtFrameCount = (TextView) findViewById(R.id.txtFrameCount);
		txtIncompleteFrameCount = (TextView) findViewById(R.id.txtIncompleteFrameCount);
		mCHTextView = (TextView) findViewById(R.id.CH_textview);
		CH_button = (ImageButton) findViewById(R.id.CH_button);

		btn_speaker = (ImageButton) findViewById(R.id.btn_speaker);

		if (mIsRecording) {
			button_toolbar_recording
					.setBackgroundResource(R.drawable.btn_recording_switch_stop);
		}

		if (mIsListening) {
			button_toolbar_speaker
					.setBackgroundResource(R.drawable.btn_speaker_on_switch);
			linSpeaker.setVisibility(View.VISIBLE);
			nullLayout.setVisibility(View.GONE);
		}

		if (isOpenLinQVGA) {
			button_toolbar_QVGA
					.setBackgroundResource(R.drawable.btn_qvga_enable_switch);
			linQVGA.setVisibility(View.VISIBLE);
			nullLayout.setVisibility(View.GONE);
		}

		if (isOpenLinEmode) {
			button_toolbar_EMODE
					.setBackgroundResource(R.drawable.btn_emode_enable_switch);
			linPnlemode.setVisibility(View.VISIBLE);
			nullLayout.setVisibility(View.GONE);
		}

		if (mCamera != null && mCamera.isSessionConnected()
				&& mCamera.getMultiStreamSupported(0)
				&& mCamera.getSupportedStream().length > 1) {
			CH_button.setVisibility(View.VISIBLE);
		} else {
			CH_button.setVisibility(View.GONE);
		}

		if (txtConnectionStatus != null) {
			if (getText(R.string.connstus_connecting).toString().equals(
					mConnStatus)) {
				txtConnectionStatus
						.setBackgroundResource(R.drawable.live_unknow);
			} else if (getText(R.string.connstus_connected).toString().equals(
					mConnStatus)) {
				txtConnectionStatus
						.setBackgroundResource(R.drawable.live_online);
			} else {
				txtConnectionStatus
						.setBackgroundResource(R.drawable.live_offline);
			}
		}
		;
		txtConnectionStatus.setText(mConnStatus);

		txtConnectionSlash.setText("");
		txtResolutionSlash.setText("");
		txtShowFPS.setText("");
		txtFPSSlash.setText("");
		txtShowBPS.setText("");
		txtOnlineNumberSlash.setText("");
		txtShowFrameRatio.setText("");
		txtFrameCountSlash.setText("");
		txtRecvFrmSlash.setText("");
		txtPerformance
				.setText(getPerformance((int) (((float) mCamera
						.getDispFrmPreSec() / (float) mCamera
						.getRecvFrmPreSec()) * 100)));

		txtConnectionMode.setVisibility(View.GONE);
		txtFrameRate.setVisibility(View.GONE);
		txtBitRate.setVisibility(View.GONE);
		txtFrameCount.setVisibility(View.GONE);
		txtIncompleteFrameCount.setVisibility(View.GONE);
		txtRecvFrmPreSec.setVisibility(View.GONE);
		txtDispFrmPreSeco.setVisibility(View.GONE);

		CH_button.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View arg0) {

				final AlertDialog dlg = new AlertDialog.Builder(
						LiveViewActivity.this).create();
				ListView view = new ListView(LiveViewActivity.this);
				dlg.setView(view);
				dlg.setCanceledOnTouchOutside(true);
				Window window = dlg.getWindow();
				WindowManager.LayoutParams lp = window.getAttributes();
				// lp.y = -64;
				lp.dimAmount = 0f;

				ArrayAdapter<SStreamDef> adapter = new ArrayAdapter<AVIOCTRLDEFs.SStreamDef>(
						LiveViewActivity.this,
						android.R.layout.simple_list_item_1);
				for (SStreamDef streamDef : mCamera.getSupportedStream())
					adapter.add(streamDef);

				view.setAdapter(adapter);
				view.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						if (monitor != null)
							monitor.deattachCamera();
						mCamera.stopShow(mSelectedChannel);
						mCamera.stopListening(mSelectedChannel);
						mCamera.stopSpeaking(mSelectedChannel);

						try {
							Thread.sleep(500);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						System.out.println("OnSpinStreamItemSelected: " + arg2);
						mSelectedChannel = arg2;
						mCHTextView.setText("CH" + (mSelectedChannel + 1));
						if (mCamera != null
								&& mCamera.getMultiStreamSupported(0)
								&& mCamera.getSupportedStream().length > 1)
							getSupportActionBar().setSubtitle(
									getText(R.string.dialog_LiveView)
											.toString()
											+ " : "
											+ mDevice.NickName
											+ " - CH"
											+ (mSelectedChannel + 1));
						else
							getSupportActionBar().setSubtitle(
									getText(R.string.dialog_LiveView)
											.toString()
											+ " : "
											+ mDevice.NickName);

						if (monitor != null) {
							monitor.enableDither(mCamera.mEnableDither);
							monitor.attachCamera(mCamera, mSelectedChannel);
						}
						mCamera.startShow(mSelectedChannel, true,
								m_RunSoftDecode, m_RunSoftDecode2);

						if (mIsListening)
							mCamera.startListening(mSelectedChannel,
									mIsRecording);
						if (mIsSpeaking)
							mCamera.startSpeaking(mSelectedChannel);

						wait_receive = true;
						dlg.dismiss();
					}
				});

				dlg.show();

			}
		});

		wait_receive = true;

	}

	private void setupViewInLandscapeLayout_wait_Mediacodec() {
		Log.i("bb", "天啊 神奇的东西第一次出现了  Mediacodec");
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getWindow().clearFlags(
				WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
		ActionBar actionBar = getActionBar();
		actionBar.hide();

		switch (Camera.nCodecId_temp) {

		case AVFrame.MEDIA_CODEC_VIDEO_MJPEG:
			setContentView(R.layout.live_view_landscape);
			break;

		case AVFrame.MEDIA_CODEC_VIDEO_H264:
			setContentView(R.layout.live_view_landscape_h264);
			break;

		case AVFrame.MEDIA_CODEC_VIDEO_MPEG4:
			setContentView(R.layout.live_view_landscape_mpeg4);
			break;

		default:
			setContentView(R.layout.live_view_landscape);
			break;
		}

		toolbarScrollView = (HorizontalScrollView) findViewById(R.id.ScrollView_toolbar);
		if (toolbarScrollView != null)
			toolbarScrollView.setHorizontalFadingEdgeEnabled(false);
		// toolbar_layout_head = (RelativeLayout)
		// findViewById(R.id.toolbar_layout_head);

		nullLayout = (LinearLayout) findViewById(R.id.null_layout);

		linPnlCameraInfo = (LinearLayout) findViewById(R.id.pnlCameraInfo);

		linQVGA = (RelativeLayout) findViewById(R.id.qvga_layout);
		linQVGA.setVisibility(View.GONE);
		linSpeaker = (RelativeLayout) findViewById(R.id.speaker_layout);
		linSpeaker.setVisibility(View.GONE);

		linPnlemode = (RelativeLayout) findViewById(R.id.emode_layout);
		linPnlemode.setVisibility(View.GONE);

		// toolbar
		button_toolbar_speaker = (ImageButton) findViewById(R.id.button_speaker);
		button_toolbar_recording = (ImageButton) findViewById(R.id.button_recording);
		button_toolbar_snapshot = (ImageButton) findViewById(R.id.button_snapshot);
		button_toolbar_mirror = (ImageButton) findViewById(R.id.button_mirror);
		button_toolbar_mirror_rl = (ImageButton) findViewById(R.id.button_mirror_rl);
		button_toolbar_SET = (ImageButton) findViewById(R.id.button_SET);
		button_toolbar_QVGA = (ImageButton) findViewById(R.id.button_QVGA);
		button_toolbar_EMODE = (ImageButton) findViewById(R.id.button_EMODE);

		myScrollView = (VerticalScrollView) findViewById(R.id.scrollView);
		myHorScrollView = (HorizontalScrollView) findViewById(R.id.horizontalScrollView);

		qvga_button1 = (Button) findViewById(R.id.qvga_button1);
		qvga_button2 = (Button) findViewById(R.id.qvga_button2);
		qvga_button3 = (Button) findViewById(R.id.qvga_button3);
		qvga_button4 = (Button) findViewById(R.id.qvga_button4);
		qvga_button5 = (Button) findViewById(R.id.qvga_button5);
		setQulityButtonColor(false, 0);
		btn_zoom_add = (ImageButton) findViewById(R.id.btn_zoom_add);
		btn_zoom_sub = (ImageButton) findViewById(R.id.btn_zoom_sub);

		btn_zoom_add.setOnTouchListener(addOntouch);

		btn_zoom_sub.setOnTouchListener(subOntouch);

		qvga_button1.setOnClickListener(QVGAClick);
		qvga_button2.setOnClickListener(QVGAClick);
		qvga_button3.setOnClickListener(QVGAClick);
		qvga_button4.setOnClickListener(QVGAClick);
		qvga_button5.setOnClickListener(QVGAClick);

		emode_button1 = (Button) findViewById(R.id.emode_button1);
		emode_button2 = (Button) findViewById(R.id.emode_button2);
		emode_button3 = (Button) findViewById(R.id.emode_button3);
		emode_button4 = (Button) findViewById(R.id.emode_button4);
		setEMode(EnvironmentMode);
		emode_button1.setOnClickListener(EmodeClick);
		emode_button2.setOnClickListener(EmodeClick);
		emode_button3.setOnClickListener(EmodeClick);
		emode_button4.setOnClickListener(EmodeClick);

		btn_speaker = (ImageButton) findViewById(R.id.btn_speaker);
		btn_speaker.setOnTouchListener(touch);
		button_toolbar_presetting = (ImageButton) findViewById(R.id.button_presetting);
		button_toolbar_presetting.setOnClickListener(ToolBarClick);
		button_toolbar_cruise = (ImageButton) findViewById(R.id.button_cruise);
		button_toolbar_cruise.setOnClickListener(ToolBarClick);
		btn_cru1 = (ImageButton) findViewById(R.id.btn_cruise1);
		btn_cru2 = (ImageButton) findViewById(R.id.btn_cruise2);
		btn_cru3 = (ImageButton) findViewById(R.id.btn_cruise3);
		btn_cru1.setOnClickListener(CruiseClick);
		btn_cru2.setOnClickListener(CruiseClick);
		btn_cru3.setOnClickListener(CruiseClick);
		btn_pre1 = (ImageButton) findViewById(R.id.btn_pre1);
		btn_pre2 = (ImageButton) findViewById(R.id.btn_pre2);
		btn_pre3 = (ImageButton) findViewById(R.id.btn_pre3);
		btn_pre4 = (ImageButton) findViewById(R.id.btn_pre4);
		btn_pre1.setOnClickListener(PreClick);
		btn_pre2.setOnClickListener(PreClick);
		btn_pre3.setOnClickListener(PreClick);
		btn_pre4.setOnClickListener(PreClick);
		btn_pre1.setOnLongClickListener(longClick);
		btn_pre2.setOnLongClickListener(longClick);
		btn_pre3.setOnLongClickListener(longClick);
		btn_pre4.setOnLongClickListener(longClick);
		toolbar_layout = (RelativeLayout) findViewById(R.id.toolbar_layout);
		toolbar_layout2 = (RelativeLayout) findViewById(R.id.toolbar_layout2);
		button_toolbar_speaker.setOnClickListener(ToolBarClick);
		toolbar_layout3 = (RelativeLayout) findViewById(R.id.toolbar_layout3);
		button_toolbar_recording.setOnClickListener(ToolBarClick);
		button_toolbar_snapshot.setOnClickListener(ToolBarClick);
		button_toolbar_mirror.setOnClickListener(ToolBarClick);
		button_toolbar_mirror_rl.setOnClickListener(ToolBarClick);
		button_toolbar_SET.setOnClickListener(ToolBarClick);
		button_toolbar_QVGA.setOnClickListener(ToolBarClick);
		button_toolbar_EMODE.setOnClickListener(ToolBarClick);

		toolbar_layout.setVisibility(View.GONE);
		if (toolbar_layout_head != null)
			toolbar_layout_head.setVisibility(View.GONE);
		isShowToolBar = false;

		if (mIsRecording) {
			button_toolbar_recording
					.setBackgroundResource(R.drawable.btn_recording_switch_stop);
		}

		if (mIsListening) {
			button_toolbar_speaker
					.setBackgroundResource(R.drawable.btn_speaker_on_switch);
			linSpeaker.setVisibility(View.VISIBLE);
			nullLayout.setVisibility(View.GONE);
			toolbar_layout.setVisibility(View.VISIBLE);
			if (toolbar_layout_head != null)
				toolbar_layout_head.setVisibility(View.VISIBLE);
			isShowToolBar = true;
		}

		if (isOpenLinQVGA) {
			button_toolbar_QVGA
					.setBackgroundResource(R.drawable.btn_qvga_enable_switch);
			linQVGA.setVisibility(View.VISIBLE);
			nullLayout.setVisibility(View.GONE);
			toolbar_layout.setVisibility(View.VISIBLE);
			if (toolbar_layout_head != null)
				toolbar_layout_head.setVisibility(View.VISIBLE);
			isShowToolBar = true;
		}

		if (isOpenLinEmode) {
			button_toolbar_EMODE
					.setBackgroundResource(R.drawable.btn_emode_enable_switch);
			linPnlemode.setVisibility(View.VISIBLE);
			nullLayout.setVisibility(View.GONE);
			toolbar_layout.setVisibility(View.VISIBLE);
			if (toolbar_layout_head != null)
				toolbar_layout_head.setVisibility(View.VISIBLE);
			isShowToolBar = true;
		}

		if (Build.VERSION.SDK_INT < BUILD_VERSION_CODES_ICE_CREAM_SANDWICH) {

			bg.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
			getSupportActionBar().setBackgroundDrawable(bg);

			bgSplit.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
			getSupportActionBar().setSplitBackgroundDrawable(bgSplit);
		}

		if (mCamera != null && mCamera.getMultiStreamSupported(0)
				&& mCamera.getSupportedStream().length > 1)
			getSupportActionBar().setSubtitle(
					getText(R.string.dialog_LiveView).toString() + " : "
							+ mDevice.NickName + " - CH"
							+ (mSelectedChannel + 1));
		else
			getSupportActionBar().setSubtitle(
					getText(R.string.dialog_LiveView).toString() + " : "
							+ mDevice.NickName);

		txtConnectionStatus = null;
		txtConnectionMode = null;
		txtResolution = null;
		txtFrameRate = null;
		txtBitRate = null;
		txtOnlineNumber = null;
		txtFrameCount = null;
		txtIncompleteFrameCount = null;
		txtRecvFrmPreSec = null;
		txtDispFrmPreSeco = null;
		txtPerformance = null;

		if (monitor != null)
			monitor.deattachCamera();

		monitor = null;
		monitor = (IMonitor) findViewById(R.id.monitor);
		monitor.cleanFrameQueue();
		monitor.setMaxZoom(3.0f);
		monitor.enableDither(mCamera.mEnableDither);
		monitor.attachCamera(mCamera, mSelectedChannel);
		monitor.SetOnMonitorClickListener(this);
		monitor.setMediaCodecListener(this);

		// calculate surface view size
		Display display = getWindowManager().getDefaultDisplay();
		Point size = new Point();
		display.getSize(size);
		int width = size.x;
		int height = size.y;

		final SurfaceView surfaceView = (SurfaceView) monitor;
		surfaceView.getLayoutParams().width = width;
		surfaceView.getLayoutParams().height = height;
		mMiniVideoHeight = surfaceView.getLayoutParams().height;
		mMiniVideoWidth = surfaceView.getLayoutParams().width;
		surfaceView.setLayoutParams(surfaceView.getLayoutParams());
		if (myHorScrollView != null) {
			myHorScrollView.setOnTouchListener(new OnTouchListener() {
				@Override
				public boolean onTouch(View view, MotionEvent event) {
					monitor.HorizontalScrollTouch(view, event);
					return false;
				}
			});
		}
	}

	private void setupViewInLandscapeLayout_wait() {
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getWindow().clearFlags(
				WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
		ActionBar actionBar = getActionBar();
		actionBar.hide();

		setContentView(R.layout.live_view_landscape);
		// if (toolbarScrollView != null) {
		// toolbarScrollView = (HorizontalScrollView)
		// findViewById(R.id.ScrollView_toolbar);
		// toolbarScrollView.setHorizontalFadingEdgeEnabled(false);
		// }
		// toolbar_layout_head = (RelativeLayout)
		// findViewById(R.id.toolbar_layout_head);

		// toolbar

		toolbar_layout = (RelativeLayout) findViewById(R.id.toolbar_layout);

		toolbar_layout.setVisibility(View.GONE);

		isShowToolBar = false;

		if (Build.VERSION.SDK_INT < BUILD_VERSION_CODES_ICE_CREAM_SANDWICH) {

			bg.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
			getSupportActionBar().setBackgroundDrawable(bg);

			bgSplit.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT);
			getSupportActionBar().setSplitBackgroundDrawable(bgSplit);
		}
		btn_restore = (ImageButton) findViewById(R.id.btn_restore);
		btn_restore.setOnClickListener(this);
		infrared_open = (Button) findViewById(R.id.infrared_open);
		infrared_open.setOnClickListener(InfraredClick);
		infrared_close = (Button) findViewById(R.id.infrared_close);
		infrared_close.setOnClickListener(InfraredClick);
		infrared_auto = (Button) findViewById(R.id.infrared_auto);
		infrared_auto.setOnClickListener(InfraredClick);
		button_brightness = (ImageButton) findViewById(R.id.button_brightness);
		button_brightness.setOnClickListener(this);
		button_contrast = (ImageButton) findViewById(R.id.button_contrast);
		button_contrast.setOnClickListener(this);
		mVerSeekBar_Brightness = (VerticalSeekBar) findViewById(R.id.seekbar_Brightness);
		mVerSeekBar_Brightness.setOnSeekBarChangeListener(br);
		btn_infrared = (ImageButton) findViewById(R.id.btn_infrared);
		btn_infrared.setOnClickListener(ToolBarClick);
		infrared_layout = (RelativeLayout) findViewById(R.id.infrared_layout);
		infrared_layout.setVisibility(View.GONE);
		if (isOpenInfrared) {
			btn_infrared.setBackgroundResource(R.drawable.infrared_click);
			infrared_layout.setVisibility(View.VISIBLE);
		}
		mVerSeekBar_Brightness.setProgress(mBrightness_Level);
		seekbar_Contrast = (VerticalSeekBar) findViewById(R.id.seekbar_Contrast);
		seekbar_Contrast.setOnSeekBarChangeListener(cr);
		seekbar_Contrast.setProgress(mContrast_Level);
		if (mCamera != null && mCamera.getMultiStreamSupported(0)
				&& mCamera.getSupportedStream().length > 1)
			getSupportActionBar().setSubtitle(
					getText(R.string.dialog_LiveView).toString() + " : "
							+ mDevice.NickName + " - CH"
							+ (mSelectedChannel + 1));
		else
			getSupportActionBar().setSubtitle(
					getText(R.string.dialog_LiveView).toString() + " : "
							+ mDevice.NickName);

		if (monitor != null)
			monitor.deattachCamera();

		monitor = null;
		monitor = (IMonitor) findViewById(R.id.monitor);
		monitor.setMaxZoom(3.0f);
		monitor.enableDither(mCamera.mEnableDither);
		monitor.attachCamera(mCamera, mSelectedChannel);
		monitor.SetOnMonitorClickListener(this);
	}

	private void setupViewInPortraitLayout_wait_Mediacodec() {

		getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getWindow().clearFlags(
				WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);

		ActionBar actionBar = getActionBar();
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
		actionBar.setCustomView(R.layout.titlebar);
		actionBar.show();

		setContentView(R.layout.advanced_settings);
		txt_title = (TextView) this.findViewById(R.id.bar_text);
		txt_title.setText(mDevice.NickName);

		switch (Camera.nCodecId_temp) {

		case AVFrame.MEDIA_CODEC_VIDEO_MJPEG:
			setContentView(R.layout.live_view_portrait);
			break;

		case AVFrame.MEDIA_CODEC_VIDEO_H264:
			setContentView(R.layout.live_view_portrait_h264);
			break;

		case AVFrame.MEDIA_CODEC_VIDEO_MPEG4:
			setContentView(R.layout.live_view_portrait_mpeg4);
			break;

		default:
			setContentView(R.layout.live_view_portrait);
			break;
		}

		// toolbarScrollView = (HorizontalScrollView)
		// findViewById(R.id.ScrollView_toolbar);
		// if (toolbarScrollView != null)
		// toolbarScrollView.setHorizontalFadingEdgeEnabled(false);
		toolbar_layout_head = null;

		toolbar_layout = (RelativeLayout) findViewById(R.id.toolbar_layout);

		myScrollView = (VerticalScrollView) findViewById(R.id.scrollView);
		myHorScrollView = (HorizontalScrollView) findViewById(R.id.horizontalScrollView);

		if (monitor != null)
			monitor.deattachCamera();

		monitor = null;
		monitor = (IMonitor) findViewById(R.id.monitor);
		// monitor.setZOrderMediaOverlay(false);
		monitor.cleanFrameQueue();
		monitor.setMaxZoom(3.0f);
		monitor.enableDither(mCamera.mEnableDither);
		monitor.attachCamera(mCamera, mSelectedChannel);
		monitor.setMediaCodecListener(this);

		// calculate surface view size
		Display display = getWindowManager().getDefaultDisplay();
		Point size = new Point();
		display.getSize(size);
		int width = size.x;
		int height = size.y;

		final SurfaceView surfaceView = (SurfaceView) monitor;
		surfaceView.getLayoutParams().width = width;
		handler.post(new Runnable() {
			@Override
			public void run() {
				if (myScrollView.getMeasuredHeight() == 0) {
					handler.postDelayed(this, 200);
				} else {
					surfaceView.getLayoutParams().height = myScrollView
							.getMeasuredHeight();
					mMiniVideoHeight = surfaceView.getLayoutParams().height;
					mMiniVideoWidth = surfaceView.getLayoutParams().width;
					surfaceView.setLayoutParams(surfaceView.getLayoutParams());
				}
			}
		});
		if (myHorScrollView != null) {
			myHorScrollView.setOnTouchListener(new OnTouchListener() {
				@Override
				public boolean onTouch(View view, MotionEvent event) {
					monitor.HorizontalScrollTouch(view, event);
					return false;
				}
			});
		}
	}

	private void setupViewInPortraitLayout_wait() {
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getWindow().clearFlags(
				WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);

		ActionBar actionBar = getActionBar();
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
		actionBar.setCustomView(R.layout.titlebar);
		actionBar.show();

		setContentView(R.layout.advanced_settings);
		txt_title = (TextView) this.findViewById(R.id.bar_text);
		txt_title.setText(mDevice.NickName);
		setContentView(R.layout.live_view_portrait);

		toolbarScrollView = (HorizontalScrollView) findViewById(R.id.ScrollView_toolbar);
		if (toolbarScrollView != null)
			toolbarScrollView.setHorizontalFadingEdgeEnabled(false);
		toolbar_layout_head = null;

		nullLayout = (LinearLayout) findViewById(R.id.null_layout);

		linPnlCameraInfo = (LinearLayout) findViewById(R.id.pnlCameraInfo);

		linQVGA = (RelativeLayout) findViewById(R.id.qvga_layout);
		linQVGA.setVisibility(View.GONE);
		linSpeaker = (RelativeLayout) findViewById(R.id.speaker_layout);
		linSpeaker.setVisibility(View.GONE);
		linPnlemode = (RelativeLayout) findViewById(R.id.emode_layout);
		linPnlemode.setVisibility(View.GONE);

		// toolbar
		button_toolbar_speaker = (ImageButton) findViewById(R.id.button_speaker);
		button_toolbar_recording = (ImageButton) findViewById(R.id.button_recording);
		button_toolbar_snapshot = (ImageButton) findViewById(R.id.button_snapshot);
		button_toolbar_mirror = (ImageButton) findViewById(R.id.button_mirror);
		button_toolbar_mirror_rl = (ImageButton) findViewById(R.id.button_mirror_rl);
		button_toolbar_SET = (ImageButton) findViewById(R.id.button_SET);
		button_toolbar_QVGA = (ImageButton) findViewById(R.id.button_QVGA);
		button_toolbar_EMODE = (ImageButton) findViewById(R.id.button_EMODE);
		button_toolbar_presetting = (ImageButton) findViewById(R.id.button_presetting);
		button_toolbar_presetting.setOnClickListener(ToolBarClick);
		button_toolbar_cruise = (ImageButton) findViewById(R.id.button_cruise);
		button_toolbar_cruise.setOnClickListener(ToolBarClick);
		btn_cru1 = (ImageButton) findViewById(R.id.btn_cruise1);
		btn_cru2 = (ImageButton) findViewById(R.id.btn_cruise2);
		btn_cru3 = (ImageButton) findViewById(R.id.btn_cruise3);
		btn_cru1.setOnClickListener(CruiseClick);
		btn_cru2.setOnClickListener(CruiseClick);
		btn_cru3.setOnClickListener(CruiseClick);
		btn_pre1 = (ImageButton) findViewById(R.id.btn_pre1);
		btn_pre2 = (ImageButton) findViewById(R.id.btn_pre2);
		btn_pre3 = (ImageButton) findViewById(R.id.btn_pre3);
		btn_pre4 = (ImageButton) findViewById(R.id.btn_pre4);
		btn_pre1.setOnClickListener(PreClick);
		btn_pre2.setOnClickListener(PreClick);
		btn_pre3.setOnClickListener(PreClick);
		btn_pre4.setOnClickListener(PreClick);
		btn_pre1.setOnLongClickListener(longClick);
		btn_pre2.setOnLongClickListener(longClick);
		btn_pre3.setOnLongClickListener(longClick);
		btn_pre4.setOnLongClickListener(longClick);
		toolbar_layout = (RelativeLayout) findViewById(R.id.toolbar_layout);
		toolbar_layout2 = (RelativeLayout) findViewById(R.id.toolbar_layout2);
		toolbar_layout3 = (RelativeLayout) findViewById(R.id.toolbar_layout3);
		qvga_button1 = (Button) findViewById(R.id.qvga_button1);
		qvga_button2 = (Button) findViewById(R.id.qvga_button2);
		qvga_button3 = (Button) findViewById(R.id.qvga_button3);
		qvga_button4 = (Button) findViewById(R.id.qvga_button4);
		qvga_button5 = (Button) findViewById(R.id.qvga_button5);
		setQulityButtonColor(false, 0);
		btn_zoom_add = (ImageButton) findViewById(R.id.btn_zoom_add);
		btn_zoom_sub = (ImageButton) findViewById(R.id.btn_zoom_sub);
		btn_zoom_add.setOnTouchListener(addOntouch);
		btn_zoom_sub.setOnTouchListener(subOntouch);

		qvga_button1.setOnClickListener(QVGAClick);
		qvga_button2.setOnClickListener(QVGAClick);
		qvga_button3.setOnClickListener(QVGAClick);
		qvga_button4.setOnClickListener(QVGAClick);
		qvga_button5.setOnClickListener(QVGAClick);

		emode_button1 = (Button) findViewById(R.id.emode_button1);
		emode_button2 = (Button) findViewById(R.id.emode_button2);
		emode_button3 = (Button) findViewById(R.id.emode_button3);
		emode_button4 = (Button) findViewById(R.id.emode_button4);
		setEMode(EnvironmentMode);
		emode_button1.setOnClickListener(EmodeClick);
		emode_button2.setOnClickListener(EmodeClick);
		emode_button3.setOnClickListener(EmodeClick);
		emode_button4.setOnClickListener(EmodeClick);

		button_toolbar_speaker.setOnClickListener(ToolBarClick);

		button_toolbar_recording.setOnClickListener(ToolBarClick);
		button_toolbar_snapshot.setOnClickListener(ToolBarClick);
		button_toolbar_mirror.setOnClickListener(ToolBarClick);
		button_toolbar_mirror_rl.setOnClickListener(ToolBarClick);
		button_toolbar_SET.setOnClickListener(ToolBarClick);
		button_toolbar_QVGA.setOnClickListener(ToolBarClick);
		button_toolbar_EMODE.setOnClickListener(ToolBarClick);

		txtConnectionSlash = (TextView) findViewById(R.id.txtConnectionSlash);
		txtResolutionSlash = (TextView) findViewById(R.id.txtResolutionSlash);
		txtShowFPS = (TextView) findViewById(R.id.txtShowFPS);
		txtFPSSlash = (TextView) findViewById(R.id.txtFPSSlash);
		txtShowBPS = (TextView) findViewById(R.id.txtShowBPS);
		txtShowOnlineNumber = (TextView) findViewById(R.id.txtShowOnlineNumber);
		txtOnlineNumberSlash = (TextView) findViewById(R.id.txtOnlineNumberSlash);
		txtShowFrameRatio = (TextView) findViewById(R.id.txtShowFrameRatio);
		txtFrameCountSlash = (TextView) findViewById(R.id.txtFrameCountSlash);
		txtQuality = (TextView) findViewById(R.id.txtQuality);
		txtDispFrmPreSeco = (TextView) findViewById(R.id.txtDispFrmPreSeco);
		txtRecvFrmSlash = (TextView) findViewById(R.id.txtRecvFrmSlash);
		txtRecvFrmPreSec = (TextView) findViewById(R.id.txtRecvFrmPreSec);
		txtPerformance = (TextView) findViewById(R.id.txtPerformance);

		txtConnectionStatus = (TextView) findViewById(R.id.txtConnectionStatus);
		txtConnectionMode = (TextView) findViewById(R.id.txtConnectionMode);
		txtResolution = (TextView) findViewById(R.id.txtResolution);
		txtFrameRate = (TextView) findViewById(R.id.txtFrameRate);
		txtBitRate = (TextView) findViewById(R.id.txtBitRate);
		txtOnlineNumber = (TextView) findViewById(R.id.txtOnlineNumber);
		txtFrameCount = (TextView) findViewById(R.id.txtFrameCount);
		txtIncompleteFrameCount = (TextView) findViewById(R.id.txtIncompleteFrameCount);
		mCHTextView = (TextView) findViewById(R.id.CH_textview);
		CH_button = (ImageButton) findViewById(R.id.CH_button);

		btn_speaker = (ImageButton) findViewById(R.id.btn_speaker);
		btn_speaker.setOnTouchListener(touch);

		if (mIsRecording) {
			button_toolbar_recording
					.setBackgroundResource(R.drawable.btn_recording_switch_stop);
		}

		if (mIsListening) {
			button_toolbar_speaker
					.setBackgroundResource(R.drawable.btn_speaker_on_switch);
			linSpeaker.setVisibility(View.VISIBLE);
			nullLayout.setVisibility(View.GONE);
		}

		if (isOpenLinQVGA) {
			button_toolbar_QVGA
					.setBackgroundResource(R.drawable.btn_qvga_enable_switch);
			linQVGA.setVisibility(View.VISIBLE);
			nullLayout.setVisibility(View.GONE);
		}

		if (isOpenLinEmode) {
			button_toolbar_EMODE
					.setBackgroundResource(R.drawable.btn_emode_enable_switch);
			linPnlemode.setVisibility(View.VISIBLE);
			nullLayout.setVisibility(View.GONE);
		}

		if (mCamera != null && mCamera.isSessionConnected()
				&& mCamera.getMultiStreamSupported(0)
				&& mCamera.getSupportedStream().length > 1) {
			CH_button.setVisibility(View.VISIBLE);
		} else {
			CH_button.setVisibility(View.GONE);
		}

		if (txtConnectionStatus != null) {
			if (getText(R.string.connstus_connecting).toString().equals(
					mConnStatus)) {
				txtConnectionStatus
						.setBackgroundResource(R.drawable.live_unknow);
			} else if (getText(R.string.connstus_connected).toString().equals(
					mConnStatus)) {
				txtConnectionStatus
						.setBackgroundResource(R.drawable.live_online);
			} else {
				txtConnectionStatus
						.setBackgroundResource(R.drawable.live_offline);
			}
		}
		;
		txtConnectionStatus.setText(mConnStatus);

		txtConnectionSlash.setText("");
		txtResolutionSlash.setText("");
		txtShowFPS.setText("");
		txtFPSSlash.setText("");
		txtShowBPS.setText("");
		txtOnlineNumberSlash.setText("");
		txtShowFrameRatio.setText("");
		txtFrameCountSlash.setText("");
		txtRecvFrmSlash.setText("");
		txtPerformance
				.setText(getPerformance((int) (((float) mCamera
						.getDispFrmPreSec() / (float) mCamera
						.getRecvFrmPreSec()) * 100)));

		txtConnectionMode.setVisibility(View.GONE);
		txtFrameRate.setVisibility(View.GONE);
		txtBitRate.setVisibility(View.GONE);
		txtFrameCount.setVisibility(View.GONE);
		txtIncompleteFrameCount.setVisibility(View.GONE);
		txtRecvFrmPreSec.setVisibility(View.GONE);
		txtDispFrmPreSeco.setVisibility(View.GONE);

		linPnlCameraInfo.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View arg0) {

				MultiViewActivity.nShowMessageCount++;
				showMessage();

			}
		});

		CH_button.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View arg0) {

				final AlertDialog dlg = new AlertDialog.Builder(
						LiveViewActivity.this).create();
				ListView view = new ListView(LiveViewActivity.this);
				dlg.setView(view);
				dlg.setCanceledOnTouchOutside(true);
				Window window = dlg.getWindow();
				WindowManager.LayoutParams lp = window.getAttributes();
				// lp.y = -64;
				lp.dimAmount = 0f;

				ArrayAdapter<SStreamDef> adapter = new ArrayAdapter<AVIOCTRLDEFs.SStreamDef>(
						LiveViewActivity.this,
						android.R.layout.simple_list_item_1);
				for (SStreamDef streamDef : mCamera.getSupportedStream())
					adapter.add(streamDef);

				view.setAdapter(adapter);
				view.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {

						monitor.deattachCamera();
						mCamera.stopShow(mSelectedChannel);
						mCamera.stopListening(mSelectedChannel);
						mCamera.stopSpeaking(mSelectedChannel);

						try {
							Thread.sleep(500);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						System.out.println("OnSpinStreamItemSelected: " + arg2);
						mSelectedChannel = arg2;
						mCHTextView.setText("CH" + (mSelectedChannel + 1));
						if (mCamera != null
								&& mCamera.getMultiStreamSupported(0)
								&& mCamera.getSupportedStream().length > 1)
							getSupportActionBar().setSubtitle(
									getText(R.string.dialog_LiveView)
											.toString()
											+ " : "
											+ mDevice.NickName
											+ " - CH"
											+ (mSelectedChannel + 1));
						else
							getSupportActionBar().setSubtitle(
									getText(R.string.dialog_LiveView)
											.toString()
											+ " : "
											+ mDevice.NickName);

						monitor.enableDither(mCamera.mEnableDither);
						monitor.attachCamera(mCamera, mSelectedChannel);
						mCamera.startShow(mSelectedChannel, true,
								m_RunSoftDecode, m_RunSoftDecode2);

						if (mIsListening)
							mCamera.startListening(mSelectedChannel,
									mIsRecording);
						if (mIsSpeaking)
							mCamera.startSpeaking(mSelectedChannel);

						dlg.dismiss();
					}
				});

				dlg.show();

			}
		});

		if (monitor != null)
			monitor.deattachCamera();

		monitor = null;
		monitor = (IMonitor) findViewById(R.id.monitor);
		// monitor.setZOrderMediaOverlay(false);
		monitor.setMaxZoom(3.0f);
		monitor.enableDither(mCamera.mEnableDither);
		monitor.attachCamera(mCamera, mSelectedChannel);
		// monitor.setOnClickListener(ToolBarClick);
	}

	private void showMessage() {

		St_SInfo stSInfo = new St_SInfo();
		IOTCAPIs.IOTC_Session_Check(mCamera.getMSID(), stSInfo);

		if (MultiViewActivity.nShowMessageCount >= 10) {

			txtConnectionStatus.setText(mConnStatus);
			txtConnectionMode.setText(getSessionMode(mCamera != null ? mCamera
					.getSessionMode() : -1)
					+ " C: "
					+ IOTCAPIs.IOTC_Get_Nat_Type()
					+ ", D: "
					+ stSInfo.NatType
					+ ",R" + mCamera.getbResend());

			txtConnectionSlash.setText(" / ");
			txtResolutionSlash.setText(" / ");
			txtShowFPS.setText(getText(R.string.txtFPS));
			txtFPSSlash.setText(" / ");
			txtShowBPS.setText(getText(R.string.txtBPS));
			// txtShowOnlineNumber.setText(getText(R.string.txtOnlineNumber));
			txtOnlineNumberSlash.setText(" / ");
			txtShowFrameRatio.setText(getText(R.string.txtFrameRatio));
			txtFrameCountSlash.setText(" / ");
			txtQuality.setText(getText(R.string.txtQuality));
			txtRecvFrmSlash.setText(" / ");
			// mCamera.getDispFrmPreSec()
			txtConnectionMode.setVisibility(View.VISIBLE);
			// txtResolution.setVisibility(View.VISIBLE);
			txtFrameRate.setVisibility(View.VISIBLE);
			txtBitRate.setVisibility(View.VISIBLE);
			txtOnlineNumber.setVisibility(View.VISIBLE);
			txtFrameCount.setVisibility(View.VISIBLE);
			txtIncompleteFrameCount.setVisibility(View.VISIBLE);
			txtRecvFrmPreSec.setVisibility(View.VISIBLE);
			txtDispFrmPreSeco.setVisibility(View.VISIBLE);
		}
	}

	/**
	 * 巡航按钮监听事件
	 */
	private Button.OnClickListener CruiseClick = new Button.OnClickListener() {

		@Override
		public void onClick(View v) {

			switch (v.getId()) {
			case R.id.btn_cruise1:
				mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
						HICHIPIOCTRDEFs.IOTYPE_HICHIP_CRUISE_START,
						HICHIPIOCTRDEFs.SMsgAVIoctrlCruiseStart.parseContent(
								Camera.DEFAULT_AV_CHANNEL,
								HICHIPIOCTRDEFs.AVIOCTRL_CRUISEMODE_HORIZONTAL));
				break;
			case R.id.btn_cruise2:
				mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
						HICHIPIOCTRDEFs.IOTYPE_HICHIP_CRUISE_START,
						HICHIPIOCTRDEFs.SMsgAVIoctrlCruiseStart.parseContent(
								Camera.DEFAULT_AV_CHANNEL,
								HICHIPIOCTRDEFs.AVIOCTRL_CRUISEMODE_VERTICAL));
				break;
			case R.id.btn_cruise3:
				mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
						HICHIPIOCTRDEFs.IOTYPE_HICHIP_CRUISE_STOP,
						HICHIPIOCTRDEFs.SMsgAVIoctrlCruiseStop
								.parseContent(Camera.DEFAULT_AV_CHANNEL));
				break;

			}
		}
	};
	private Button.OnClickListener PreClick = new Button.OnClickListener() {

		@Override
		public void onClick(View v) {
			// linQVGA.setVisibility(View.GONE);
			// nullLayout.setVisibility(View.VISIBLE);
			switch (v.getId()) {
			case R.id.btn_pre1:
				mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
						HICHIPIOCTRDEFs.IOTYPE_USER_IPCAM_GETPRESET_REQ,
						HICHIPIOCTRDEFs.SMsgAVIoctrlSetPresetReq.parseContent(
								Camera.DEFAULT_AV_CHANNEL, 1));
				// ResetPre(1);
				break;
			case R.id.btn_pre2:
				// ResetPre(2);
				mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
						HICHIPIOCTRDEFs.IOTYPE_USER_IPCAM_GETPRESET_REQ,
						HICHIPIOCTRDEFs.SMsgAVIoctrlSetPresetReq.parseContent(
								Camera.DEFAULT_AV_CHANNEL, 2));
				break;
			case R.id.btn_pre3:
				// ResetPre(3);
				mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
						HICHIPIOCTRDEFs.IOTYPE_USER_IPCAM_GETPRESET_REQ,
						HICHIPIOCTRDEFs.SMsgAVIoctrlSetPresetReq.parseContent(
								Camera.DEFAULT_AV_CHANNEL, 3));
				break;
			case R.id.btn_pre4:
				// ResetPre(4);
				mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
						HICHIPIOCTRDEFs.IOTYPE_USER_IPCAM_GETPRESET_REQ,
						HICHIPIOCTRDEFs.SMsgAVIoctrlSetPresetReq.parseContent(
								Camera.DEFAULT_AV_CHANNEL, 4));
				break;
			}
		}
	};
	private Button.OnClickListener QVGAClick = new Button.OnClickListener() {

		// 画质
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			button_toolbar_QVGA
					.setBackgroundResource(R.drawable.btn_qvga_switch);
			isOpenLinQVGA = false;
			linQVGA.setVisibility(View.GONE);
			nullLayout.setVisibility(View.VISIBLE);
			switch (v.getId()) {
			case R.id.qvga_button1:
				mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
						AVIOCTRLDEFs.IOTYPE_USER_IPCAM_SETSTREAMCTRL_REQ,
						AVIOCTRLDEFs.SMsgAVIoctrlSetStreamCtrlReq.parseContent(
								mDevice.ChannelIndex, (byte) 1));
				DatabaseManager.VideoQuality(mCamera.getUID(), 1);
				setQulityButtonColor(true, 1);
				break;
			case R.id.qvga_button2:
				mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
						AVIOCTRLDEFs.IOTYPE_USER_IPCAM_SETSTREAMCTRL_REQ,
						AVIOCTRLDEFs.SMsgAVIoctrlSetStreamCtrlReq.parseContent(
								mDevice.ChannelIndex, (byte) 2));
				DatabaseManager.VideoQuality(mCamera.getUID(), 2);
				setQulityButtonColor(true, 2);
				break;
			case R.id.qvga_button3:
				mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
						AVIOCTRLDEFs.IOTYPE_USER_IPCAM_SETSTREAMCTRL_REQ,
						AVIOCTRLDEFs.SMsgAVIoctrlSetStreamCtrlReq.parseContent(
								mDevice.ChannelIndex, (byte) 3));
				DatabaseManager.VideoQuality(mCamera.getUID(), 3);
				setQulityButtonColor(true, 3);
				break;
			case R.id.qvga_button4:
				mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
						AVIOCTRLDEFs.IOTYPE_USER_IPCAM_SETSTREAMCTRL_REQ,
						AVIOCTRLDEFs.SMsgAVIoctrlSetStreamCtrlReq.parseContent(
								mDevice.ChannelIndex, (byte) 4));
				DatabaseManager.VideoQuality(mCamera.getUID(), 4);
				setQulityButtonColor(true, 4);
				break;
			case R.id.qvga_button5:
				mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
						AVIOCTRLDEFs.IOTYPE_USER_IPCAM_SETSTREAMCTRL_REQ,
						AVIOCTRLDEFs.SMsgAVIoctrlSetStreamCtrlReq.parseContent(
								mDevice.ChannelIndex, (byte) 5));
				DatabaseManager.VideoQuality(mCamera.getUID(), 5);
				setQulityButtonColor(true, 5);
				break;
			}
			setQulityButtonColor(false, 0);

			// mCamera.stopShow(mDevice.ChannelIndex);
			// mCamera.startShow(mDevice.ChannelIndex, true, m_RunSoftDecode);
			handler.postDelayed(new Runnable() {
				@Override
				public void run() {
					monitor.deattachCamera();
					monitor.cleanFrameQueue();

					mCamera.stopShow(mDevice.ChannelIndex);
					mCamera.startShow(mDevice.ChannelIndex, true,
							m_RunSoftDecode, m_RunSoftDecode2);

					monitor.attachCamera(mCamera, mSelectedChannel);
				}
			}, 2000);
		}

	};

	private Button.OnClickListener EmodeClick = new Button.OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			button_toolbar_EMODE
					.setBackgroundResource(R.drawable.btn_emode_switch);
			isOpenLinEmode = false;
			linPnlemode.setVisibility(View.GONE);
			nullLayout.setVisibility(View.VISIBLE);
			switch (v.getId()) {
			case R.id.emode_button1:
				mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
						AVIOCTRLDEFs.IOTYPE_USER_IPCAM_SET_ENVIRONMENT_REQ,
						AVIOCTRLDEFs.SMsgAVIoctrlSetEnvironmentReq
								.parseContent(mDevice.ChannelIndex, (byte) 0));
				EnvironmentMode = 0;
				setEMode(EnvironmentMode);
				break;
			case R.id.emode_button2:
				mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
						AVIOCTRLDEFs.IOTYPE_USER_IPCAM_SET_ENVIRONMENT_REQ,
						AVIOCTRLDEFs.SMsgAVIoctrlSetEnvironmentReq
								.parseContent(mDevice.ChannelIndex, (byte) 1));
				EnvironmentMode = 1;
				setEMode(EnvironmentMode);
				break;
			case R.id.emode_button3:
				mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
						AVIOCTRLDEFs.IOTYPE_USER_IPCAM_SET_ENVIRONMENT_REQ,
						AVIOCTRLDEFs.SMsgAVIoctrlSetEnvironmentReq
								.parseContent(mDevice.ChannelIndex, (byte) 2));
				break;
			case R.id.emode_button4:
				mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
						AVIOCTRLDEFs.IOTYPE_USER_IPCAM_SET_ENVIRONMENT_REQ,
						AVIOCTRLDEFs.SMsgAVIoctrlSetEnvironmentReq
								.parseContent(mDevice.ChannelIndex, (byte) 3));
				break;
			}
		}

	};
	private Button.OnClickListener InfraredClick = new Button.OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			btn_infrared.setBackgroundResource(R.drawable.infrared);
			isOpenInfrared = false;
			infrared_layout.setVisibility(View.GONE);
			switch (v.getId()) {
			case R.id.infrared_open:
				mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
						AVIOCTRLDEFs.IOTYPE_USEREX_IPCAM_SET_LED_REQ,
						AVIOCTRLDEFs.SMsgAVIoctrlGetRecordReq.parseContent(1));
				// EnvironmentMode = 0;
				// setEMode(EnvironmentMode);
				break;
			case R.id.infrared_close:
				mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
						AVIOCTRLDEFs.IOTYPE_USEREX_IPCAM_SET_LED_REQ,
						AVIOCTRLDEFs.SMsgAVIoctrlGetRecordReq.parseContent(2));
				// EnvironmentMode = 1;
				// setEMode(EnvironmentMode);
				break;
			case R.id.infrared_auto:
				mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
						AVIOCTRLDEFs.IOTYPE_USEREX_IPCAM_SET_LED_REQ,
						AVIOCTRLDEFs.SMsgAVIoctrlGetRecordReq.parseContent(0));
				break;

			}
		}

	};
	private Button.OnClickListener ToolBarClick = new Button.OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.button_cruise:
				toolbar_layout.setVisibility(View.GONE);
				toolbar_layout3.setVisibility(View.VISIBLE);
				break;
			case R.id.button_presetting:
				toolbar_layout.setVisibility(View.GONE);
				toolbar_layout2.setVisibility(View.VISIBLE);
				break;
			case R.id.button_speaker:
				inittoolar();
				if (mIsListening) {
					button_toolbar_recording.setClickable(true);
					button_toolbar_speaker
							.setBackgroundResource(R.drawable.btn_speaker_off_switch);
					linSpeaker.setVisibility(View.GONE);
					nullLayout.setVisibility(View.VISIBLE);
					mCamera.stopSpeaking(mSelectedChannel);
					mCamera.stopListening(mSelectedChannel);
					mIsListening = false;
					mIsSpeaking = false;

				} else {
					button_toolbar_recording.setClickable(false);
					inittoolarboolean();
					mIsListening = true;
					mCamera.startListening(mSelectedChannel, mIsRecording);
					button_toolbar_speaker
							.setBackgroundResource(R.drawable.btn_speaker_on_switch);
					linSpeaker.setVisibility(View.VISIBLE);
					nullLayout.setVisibility(View.GONE);
				}
				break;
			case R.id.button_recording:
				if (mIsRecording) {
					RecordHideOther(false);
					button_toolbar_speaker.setClickable(true);
					button_toolbar_speaker.setEnabled(true);
					button_toolbar_snapshot.setEnabled(true);
					button_toolbar_mirror.setEnabled(true);
					button_toolbar_mirror_rl.setEnabled(true);
					// button_toolbar_SET.setEnabled(true);
					button_toolbar_QVGA.setEnabled(true);
					button_toolbar_EMODE.setEnabled(true);
					CH_button.setEnabled(true);
					button_toolbar_presetting.setEnabled(true);
					btn_zoom_add.setEnabled(true);
					btn_zoom_sub.setEnabled(true);
					button_toolbar_cruise.setEnabled(true);
					mCamera.stopListening(mSelectedChannel);
					mCamera.stopSpeaking(mSelectedChannel);
					button_toolbar_recording
							.setBackgroundResource(R.drawable.btn_recording_switch_start);
					// mIsSpeaking = false;
					// mIsListening = false;
					mCamera.stopRecording();
					// mCamera.setThumbnailPath(mContext);
					mIsRecording = false;
					Toast.makeText(mContext, R.string.record_syn,
							Toast.LENGTH_SHORT).show();

				} else {
					RecordHideOther(true);
					button_toolbar_speaker.setClickable(false);
					if (getAvailaleSize() <= 300) {
						Toast.makeText(mContext, R.string.recording_tips_size,
								Toast.LENGTH_SHORT).show();
					}

					if (mCamera.codec_ID_for_recording == AVFrame.MEDIA_CODEC_VIDEO_H264) {
						button_toolbar_speaker.setEnabled(false);
						button_toolbar_snapshot.setEnabled(false);
						button_toolbar_mirror.setEnabled(false);
						button_toolbar_mirror_rl.setEnabled(false);
						// button_toolbar_SET.setEnabled(false);
						button_toolbar_QVGA.setEnabled(false);
						button_toolbar_EMODE.setEnabled(false);
						CH_button.setEnabled(false);
						button_toolbar_presetting.setEnabled(false);
						btn_zoom_add.setEnabled(false);
						btn_zoom_sub.setEnabled(false);
						button_toolbar_cruise.setEnabled(false);
						mIsRecording = true;
						mCamera.startListening(mSelectedChannel, mIsRecording);
						mCamera.stopSpeaking(mSelectedChannel);
						button_toolbar_recording
								.setBackgroundResource(R.drawable.btn_recording_switch_stop);
						// mIsListening = true;
						// mIsSpeaking = false;
						File rootFolder = new File(Environment
								.getExternalStorageDirectory()
								.getAbsolutePath()
								+ "/Record/");
						File targetFolder = new File(
								rootFolder.getAbsolutePath() + "/" + mDevUID);
						if (!rootFolder.exists()) {
							try {
								rootFolder.mkdir();
							} catch (SecurityException se) {
							}
						}

						if (!targetFolder.exists()) {
							try {
								targetFolder.mkdir();
							} catch (SecurityException se) {
							}
						}
						String path = "/sdcard/Record/" + mDevUID + "/"
								+ getFileNameWithTime2();
						mCamera.startRecording(path);

						// mdlg.show();
						Toast.makeText(mContext, R.string.start_record,
								Toast.LENGTH_SHORT).show();

						// mCamera.setThumbnailPath(path,mContext);
					} else {
						Toast.makeText(mContext,
								R.string.recording_tips_format,
								Toast.LENGTH_SHORT).show();
					}

					handler.postDelayed(new Runnable() {
						@Override
						public void run() {
							if (mIsRecording) {

								button_toolbar_speaker.setEnabled(true);
								button_toolbar_snapshot.setEnabled(true);
								button_toolbar_mirror.setEnabled(true);
								button_toolbar_mirror_rl.setEnabled(true);
								// button_toolbar_SET.setEnabled(true);
								button_toolbar_QVGA.setEnabled(true);
								button_toolbar_EMODE.setEnabled(true);
								CH_button.setEnabled(true);
								button_toolbar_presetting.setEnabled(true);
								btn_zoom_add.setEnabled(true);
								btn_zoom_sub.setEnabled(true);
								button_toolbar_cruise.setEnabled(true);
								mCamera.stopListening(mSelectedChannel);
								mCamera.stopSpeaking(mSelectedChannel);
								button_toolbar_recording
										.setBackgroundResource(R.drawable.btn_recording_switch_start);
								// mIsSpeaking = false;
								// mIsListening = false;
								mCamera.stopRecording();
								// mCamera.setThumbnailPath(mContext);
								mIsRecording = false;
								// if(mdlg.isShowing())
								// mdlg.dismiss();

							}
						}
					}, 159000);
				}
				break;
			case R.id.button_snapshot:
				inittoolar();
				inittoolarboolean();
				if (mCamera != null
						&& mCamera.isChannelConnected(mSelectedChannel)) {

					if (isSDCardValid()) {

						File rootFolder = new File(Environment
								.getExternalStorageDirectory()
								.getAbsolutePath()
								+ "/Snapshot/");
						File targetFolder = new File(
								rootFolder.getAbsolutePath() + "/" + mDevUID);
						// File rootFolder = new
						// File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath()
						// + "/Snapshot");
						// File targetFolder = new
						// File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath()
						// + "/Snapshot");

						if (!rootFolder.exists()) {
							try {
								rootFolder.mkdir();
							} catch (SecurityException se) {
							}
						}

						if (!targetFolder.exists()) {

							try {
								targetFolder.mkdir();
							} catch (SecurityException se) {
							}
						}

						final String file = targetFolder.getAbsoluteFile()
								+ "/" + getFileNameWithTime();
						mFilePath = file;
						if (mCamera != null) {
							mCamera.setSnapshot(mContext, file);
						}

					} else {

						Toast.makeText(
								LiveViewActivity.this,
								LiveViewActivity.this.getText(
										R.string.tips_no_sdcard).toString(),
								Toast.LENGTH_SHORT).show();
					}
				}
				break;
			case R.id.button_mirror:
				inittoolar();
				inittoolarboolean();
				// if (LevelFlip) {
				// LevelFlip = false;
				// mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
				// AVIOCTRLDEFs.IOTYPE_USER_IPCAM_SET_VIDEOMODE_REQ,
				// AVIOCTRLDEFs.SMsgAVIoctrlSetVideoModeReq
				// .parseContent(mDevice.ChannelIndex,
				// (byte) 0));
				//
				// } else {
				// LevelFlip = true;
				// mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
				// AVIOCTRLDEFs.IOTYPE_USER_IPCAM_SET_VIDEOMODE_REQ,
				// AVIOCTRLDEFs.SMsgAVIoctrlSetVideoModeReq
				// .parseContent(mDevice.ChannelIndex,
				// (byte) 1));
				// }
				if (LevelFlip) {
					LevelFlip = false;
					if (!VerticalFlip)
						mCamera.sendIOCtrl(
								Camera.DEFAULT_AV_CHANNEL,
								AVIOCTRLDEFs.IOTYPE_USER_IPCAM_SET_VIDEOMODE_REQ,
								AVIOCTRLDEFs.SMsgAVIoctrlSetVideoModeReq
										.parseContent(mDevice.ChannelIndex,
												(byte) 0));
					else
						mCamera.sendIOCtrl(
								Camera.DEFAULT_AV_CHANNEL,
								AVIOCTRLDEFs.IOTYPE_USER_IPCAM_SET_VIDEOMODE_REQ,
								AVIOCTRLDEFs.SMsgAVIoctrlSetVideoModeReq
										.parseContent(mDevice.ChannelIndex,
												(byte) 2));

				} else {
					LevelFlip = true;
					if (!VerticalFlip)
						mCamera.sendIOCtrl(
								Camera.DEFAULT_AV_CHANNEL,
								AVIOCTRLDEFs.IOTYPE_USER_IPCAM_SET_VIDEOMODE_REQ,
								AVIOCTRLDEFs.SMsgAVIoctrlSetVideoModeReq
										.parseContent(mDevice.ChannelIndex,
												(byte) 1));
					else
						mCamera.sendIOCtrl(
								Camera.DEFAULT_AV_CHANNEL,
								AVIOCTRLDEFs.IOTYPE_USER_IPCAM_SET_VIDEOMODE_REQ,
								AVIOCTRLDEFs.SMsgAVIoctrlSetVideoModeReq
										.parseContent(mDevice.ChannelIndex,
												(byte) 3));
				}
				break;
			case R.id.button_mirror_rl:
				inittoolar();
				inittoolarboolean();
				// if (VerticalFlip) {
				// VerticalFlip = false;
				// mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
				// AVIOCTRLDEFs.IOTYPE_USER_IPCAM_SET_VIDEOMODE_REQ,
				// AVIOCTRLDEFs.SMsgAVIoctrlSetVideoModeReq
				// .parseContent(mDevice.ChannelIndex,
				// (byte) 0));
				// } else {
				// VerticalFlip = true;
				// mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
				// AVIOCTRLDEFs.IOTYPE_USER_IPCAM_SET_VIDEOMODE_REQ,
				// AVIOCTRLDEFs.SMsgAVIoctrlSetVideoModeReq
				// .parseContent(mDevice.ChannelIndex,
				// (byte) 2));
				// }
				if (VerticalFlip) {
					VerticalFlip = false;
					if (!LevelFlip)
						mCamera.sendIOCtrl(
								Camera.DEFAULT_AV_CHANNEL,
								AVIOCTRLDEFs.IOTYPE_USER_IPCAM_SET_VIDEOMODE_REQ,
								AVIOCTRLDEFs.SMsgAVIoctrlSetVideoModeReq
										.parseContent(mDevice.ChannelIndex,
												(byte) 0));
					else
						mCamera.sendIOCtrl(
								Camera.DEFAULT_AV_CHANNEL,
								AVIOCTRLDEFs.IOTYPE_USER_IPCAM_SET_VIDEOMODE_REQ,
								AVIOCTRLDEFs.SMsgAVIoctrlSetVideoModeReq
										.parseContent(mDevice.ChannelIndex,
												(byte) 1));
				} else {
					VerticalFlip = true;
					if (!LevelFlip)
						mCamera.sendIOCtrl(
								Camera.DEFAULT_AV_CHANNEL,
								AVIOCTRLDEFs.IOTYPE_USER_IPCAM_SET_VIDEOMODE_REQ,
								AVIOCTRLDEFs.SMsgAVIoctrlSetVideoModeReq
										.parseContent(mDevice.ChannelIndex,
												(byte) 2));
					else
						mCamera.sendIOCtrl(
								Camera.DEFAULT_AV_CHANNEL,
								AVIOCTRLDEFs.IOTYPE_USER_IPCAM_SET_VIDEOMODE_REQ,
								AVIOCTRLDEFs.SMsgAVIoctrlSetVideoModeReq
										.parseContent(mDevice.ChannelIndex,
												(byte) 3));
				}
				break;

			case R.id.button_SET:
				inittoolar();
				inittoolarboolean();
				Bundle extras = new Bundle();
				extras.putString("dev_uid", mDevice.UID);
				extras.putString("dev_uuid", mDevice.UUID);
				extras.putString("dev_nickname", mDevice.NickName);
				extras.putString("conn_status", mDevice.Status);
				extras.putString("view_acc", mDevice.View_Account);
				extras.putString("view_pwd", mDevice.View_Password);
				extras.putInt("camera_channel", mSelectedChannel);
				Intent intent = new Intent();
				intent.putExtras(extras);
				intent.setClass(LiveViewActivity.this, EditDeviceActivity.class);
				startActivityForResult(intent,
						MultiViewActivity.REQUEST_CODE_CAMERA_EDIT);
				break;
			case R.id.button_QVGA:

				inittoolar();

				if (isOpenLinQVGA) {
					button_toolbar_QVGA
							.setBackgroundResource(R.drawable.btn_qvga_switch);
					isOpenLinQVGA = false;
					linQVGA.setVisibility(View.GONE);
					nullLayout.setVisibility(View.VISIBLE);
				} else {
					inittoolarboolean();
					button_toolbar_QVGA
							.setBackgroundResource(R.drawable.btn_qvga_enable_switch);
					isOpenLinQVGA = true;
					linQVGA.setVisibility(View.VISIBLE);
					nullLayout.setVisibility(View.GONE);
				}
				break;
			case R.id.button_EMODE:
				inittoolar();
				if (isOpenLinEmode) {
					button_toolbar_EMODE
							.setBackgroundResource(R.drawable.btn_emode_switch);
					isOpenLinEmode = false;
					linPnlemode.setVisibility(View.GONE);
					nullLayout.setVisibility(View.VISIBLE);
				}

				else {
					inittoolarboolean();
					button_toolbar_EMODE
							.setBackgroundResource(R.drawable.btn_emode_enable_switch);
					isOpenLinEmode = true;
					linPnlemode.setVisibility(View.VISIBLE);
					nullLayout.setVisibility(View.GONE);
				}

				break;
			case R.id.btn_infrared:
				// inittoolar();
				if (isOpenInfrared) {
					btn_infrared.setBackgroundResource(R.drawable.infrared);
					isOpenInfrared = false;
					infrared_layout.setVisibility(View.GONE);
				} else {
					// inittoolarboolean();
					btn_infrared
							.setBackgroundResource(R.drawable.infrared_click);
					isOpenInfrared = true;
					infrared_layout.setVisibility(View.VISIBLE);
				}

				break;
			}

		}
	};

	private void inittoolar() {
		button_toolbar_EMODE.setBackgroundResource(R.drawable.btn_emode_switch);
		button_toolbar_speaker
				.setBackgroundResource(R.drawable.btn_speaker_off_switch);
		button_toolbar_QVGA.setBackgroundResource(R.drawable.btn_qvga_switch);
		nullLayout.setVisibility(View.VISIBLE);
		linSpeaker.setVisibility(View.GONE);
		linQVGA.setVisibility(View.GONE);
		linPnlemode.setVisibility(View.GONE);
	}

	private void inittoolarboolean() {
		if (mIsListening) {
			mCamera.stopSpeaking(mSelectedChannel);
			mCamera.stopListening(mSelectedChannel);
		}
		mIsListening = false;
		isOpenLinEmode = false;
		isOpenLinQVGA = false;
	}

	/*
	 * private void addImageGallery(File file) { ContentValues values = new
	 * ContentValues(); values.put(MediaStore.Images.Media.DATA,
	 * file.getAbsolutePath()); values.put(MediaStore.Images.Media.MIME_TYPE,
	 * "image/jpeg"); // setar isso
	 * getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
	 * values); } private boolean saveImage(String fileName, Bitmap frame) { if
	 * (fileName == null || fileName.length() <= 0) return false; boolean bErr =
	 * false; FileOutputStream fos = null; try { fos = new
	 * FileOutputStream(fileName, false);
	 * frame.compress(Bitmap.CompressFormat.JPEG, 90, fos); fos.flush();
	 * fos.close(); } catch (Exception e) { bErr = true;
	 * System.out.println("saveImage(.): " + e.getMessage()); } finally { if
	 * (bErr) { if (fos != null) { try { fos.close(); } catch (IOException e) {
	 * e.printStackTrace(); } } return false; } } addImageGallery(new
	 * File(fileName)); return true; }
	 */

	// filename: such as,M20101023_181010.jpg
	private static String getFileNameWithTime() {

		Calendar c = Calendar.getInstance();
		int mYear = c.get(Calendar.YEAR);
		int mMonth = c.get(Calendar.MONTH) + 1;
		int mDay = c.get(Calendar.DAY_OF_MONTH);
		int mHour = c.get(Calendar.HOUR_OF_DAY);
		int mMinute = c.get(Calendar.MINUTE);
		int mSec = c.get(Calendar.SECOND);
		int mMilliSec = c.get(Calendar.MILLISECOND);

		StringBuffer sb = new StringBuffer();
		sb.append("IMG_");
		sb.append(mYear);
		if (mMonth < 10)
			sb.append('0');
		sb.append(mMonth);
		if (mDay < 10)
			sb.append('0');
		sb.append(mDay);
		sb.append('_');
		if (mHour < 10)
			sb.append('0');
		sb.append(mHour);
		if (mMinute < 10)
			sb.append('0');
		sb.append(mMinute);
		if (mSec < 10)
			sb.append('0');
		sb.append(mSec);
		sb.append(".jpg");

		return sb.toString();
	}

	private static String getFileNameWithTime2() {

		Calendar c = Calendar.getInstance();
		int mYear = c.get(Calendar.YEAR);
		int mMonth = c.get(Calendar.MONTH) + 1;
		int mDay = c.get(Calendar.DAY_OF_MONTH);
		int mHour = c.get(Calendar.HOUR_OF_DAY);
		int mMinute = c.get(Calendar.MINUTE);
		int mSec = c.get(Calendar.SECOND);
		int mMilliSec = c.get(Calendar.MILLISECOND);

		StringBuffer sb = new StringBuffer();
		// sb.append("MP4_");
		sb.append(mYear);
		if (mMonth < 10)
			sb.append('0');
		sb.append(mMonth);
		if (mDay < 10)
			sb.append('0');
		sb.append(mDay);
		sb.append('_');
		if (mHour < 10)
			sb.append('0');
		sb.append(mHour);
		if (mMinute < 10)
			sb.append('0');
		sb.append(mMinute);
		if (mSec < 10)
			sb.append('0');
		sb.append(mSec);
		sb.append(".mp4");

		filename = sb.toString();

		return sb.toString();
	}

	private String getSessionMode(int mode) {

		String result = "";
		if (mode == 0)
			result = getText(R.string.connmode_p2p).toString();
		else if (mode == 1)
			result = getText(R.string.connmode_relay).toString();
		else if (mode == 2)
			result = getText(R.string.connmode_lan).toString();
		else
			result = getText(R.string.connmode_none).toString();

		return result;
	}

	private String getPerformance(int mode) {

		String result = "";
		if (mode < 30)
			result = getText(R.string.txtBad).toString();
		else if (mode < 60)
			result = getText(R.string.txtNormal).toString();
		else
			result = getText(R.string.txtGood).toString();

		return result;
	}

	private static boolean isSDCardValid() {

		return Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED);
	}

	private void quit() {

		// byte[] snapshot = null;
		// Bitmap bmp = mCamera.Snapshot(mSelectedChannel);
		// if (bmp != null) {
		// bmp = compressImage(mCamera.Snapshot(mSelectedChannel));
		// if (bmp.getWidth() * bmp.getHeight() > THUMBNAIL_LIMIT_WIDTH
		// * THUMBNAIL_LIMIT_HEIGHT) {
		// bmp = Bitmap.createScaledBitmap(bmp, THUMBNAIL_LIMIT_WIDTH,
		// THUMBNAIL_LIMIT_HEIGHT, false);
		// }
		// snapshot = DatabaseManager.getByteArrayFromBitmap(bmp);
		// }

		DatabaseManager manager = new DatabaseManager(this);
		manager.updateDeviceChannelByUID(mDevUID, mSelectedChannel);

		// if (snapshot != null) {
		// manager.updateDeviceSnapshotByUID(mDevUID, snapshot);
		// }

		if (monitor != null) {
			monitor.deattachCamera();
		}

		if (mCamera != null) {

			if (mIsListening)
				mCamera.LastAudioMode = 1;
			else if (mIsSpeaking)
				mCamera.LastAudioMode = 2;
			else
				mCamera.LastAudioMode = 0;

			mCamera.unregisterIOTCListener(this);
			mCamera.stopSpeaking(mSelectedChannel);
			mCamera.stopListening(mSelectedChannel);
			mCamera.stopShow(mSelectedChannel);
		}

		/* return values to main page */
		Bundle extras = new Bundle();
		extras.putString("dev_uuid", mDevUUID);
		extras.putString("dev_uid", mDevUID);
		extras.putString("dev_nickname", mDevice.NickName);
		// extras.putByteArray("snapshot", snapshot);
		extras.putInt("camera_channel", mSelectedChannel);
		extras.putInt("OriginallyChannelIndex", OriginallyChannelIndex);
		extras.putInt("MonitorIndex", mMonitorIndex);

		Intent intent = new Intent();
		intent.putExtras(extras);
		setResult(RESULT_OK, intent);
		finish();
	}

	private Bitmap compressImage(Bitmap image) {

		Bitmap tempBitmap = image;

		try {

			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			image.compress(Bitmap.CompressFormat.JPEG, 5, baos);
			ByteArrayInputStream isBm = new ByteArrayInputStream(
					baos.toByteArray());
			Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);
			return bitmap;

		} catch (Exception e) {
			e.printStackTrace();
		}

		return tempBitmap;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		int id = item.getItemId();

		if (id == OPT_MENU_ITEM_ALBUM) {

			File folder = new File(Environment.getExternalStorageDirectory()
					.getAbsolutePath() + "/Snapshot/" + mDevUID);
			// File folder = new
			// File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath()
			// + "/Snapshot");
			String[] allFiles = folder.list();

			if (allFiles != null && allFiles.length > 0 && monitor != null) {

				monitor.deattachCamera();

				String file = folder.getAbsolutePath() + "/"
						+ allFiles[allFiles.length - 1];

				Intent intent = new Intent(LiveViewActivity.this,
						GridViewGalleryActivity.class);
				intent.putExtra("snap", mDevUID);
				intent.putExtra("images_path", folder.getAbsolutePath());
				startActivity(intent);

			} else {
				String msg = LiveViewActivity.this.getText(
						R.string.tips_no_snapshot_found).toString();
				Toast.makeText(LiveViewActivity.this, msg, Toast.LENGTH_SHORT)
						.show();
			}

		} else if (id == OPT_MENU_ITEM_SNAPSHOT) {

			if (mCamera != null && mCamera.isChannelConnected(mSelectedChannel)) {

				if (isSDCardValid()) {

					File rootFolder = new File(Environment
							.getExternalStorageDirectory().getAbsolutePath()
							+ "/Snapshot/");
					File targetFolder = new File(rootFolder.getAbsolutePath()
							+ "/" + mDevUID);

					if (!rootFolder.exists()) {
						try {
							rootFolder.mkdir();
						} catch (SecurityException se) {
							super.onOptionsItemSelected(item);
						}
					}

					if (!targetFolder.exists()) {

						try {
							targetFolder.mkdir();
						} catch (SecurityException se) {
							super.onOptionsItemSelected(item);
						}
					}

					final String file = targetFolder.getAbsoluteFile() + "/"
							+ getFileNameWithTime();
					mFilePath = file;
					if (mCamera != null) {
						mCamera.setSnapshot(mContext, file);
					}

				} else {

					Toast.makeText(
							LiveViewActivity.this,
							LiveViewActivity.this.getText(
									R.string.tips_no_sdcard).toString(),
							Toast.LENGTH_SHORT).show();
				}
			}
		}

		else if (id == OPT_MENU_ITEM_AUDIOCTRL) {

			ArrayList<String> s = new ArrayList<String>();
			s.add(getText(R.string.txtMute).toString());
			if (mCamera.getAudioInSupported(0))
				s.add(getText(R.string.txtListen).toString());
			if (mCamera.getAudioOutSupported(0))
				s.add(getText(R.string.txtSpeak).toString());

			ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
					android.R.layout.simple_list_item_1, s);

			final AlertDialog dlg = new AlertDialog.Builder(this).create();
			dlg.setTitle(null);
			dlg.setIcon(null);

			ListView view = new ListView(this);
			view.setAdapter(adapter);
			view.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> arg0, View view,
						int position, long id) {

					if (mCamera == null)
						return;

					if (position == 1) { // Listening
						mCamera.stopSpeaking(mSelectedChannel);
						mCamera.startListening(mSelectedChannel, mIsRecording);
						mIsListening = true;
						mIsSpeaking = false;
					} else if (position == 2) { // Speaking
						mCamera.stopListening(mSelectedChannel);
						mCamera.startSpeaking(mSelectedChannel);
						mIsListening = false;
						mIsSpeaking = true;
					} else if (position == 0) { // Mute
						mCamera.stopListening(mSelectedChannel);
						mCamera.stopSpeaking(mSelectedChannel);
						mIsListening = mIsSpeaking = false;
					}

					dlg.dismiss();
					LiveViewActivity.this.invalidateOptionsMenu();
				}
			});

			dlg.setView(view);
			dlg.setCanceledOnTouchOutside(true);
			dlg.show();

		} else if (id == OPT_MENU_ITEM_AUDIO_IN) {

			if (!mIsListening) {
				mCamera.startListening(mSelectedChannel, mIsRecording);
			} else {
				mCamera.stopListening(mSelectedChannel);
			}

			mIsListening = !mIsListening;

			this.invalidateOptionsMenu();

		} else if (id == OPT_MENU_ITEM_AUDIO_OUT) {

			if (!mIsSpeaking) {
				mCamera.startSpeaking(mSelectedChannel);
			} else {
				mCamera.stopSpeaking(mSelectedChannel);
			}

			mIsSpeaking = !mIsSpeaking;

			this.invalidateOptionsMenu();
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			if (toolbar_layout2.getVisibility() == View.VISIBLE) {
				toolbar_layout.setVisibility(View.VISIBLE);
				toolbar_layout2.setVisibility(View.GONE);
			} else if (toolbar_layout3.getVisibility() == View.VISIBLE) {

				toolbar_layout.setVisibility(View.VISIBLE);
				toolbar_layout3.setVisibility(View.GONE);

			} else {
				quit();
			}
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void receiveFrameData(final Camera camera, int avChannel, Bitmap bmp) {

		if (mCamera == camera && avChannel == mSelectedChannel) {
			if (bmp.getWidth() != mVideoWidth
					|| bmp.getHeight() != mVideoHeight) {
				mVideoWidth = bmp.getWidth();
				mVideoHeight = bmp.getHeight();
			}
		}

		if (wait_receive) {
			// if (mCamera != null) {
			//
			// mCamera.stopSpeaking(mSelectedChannel);
			// mCamera.stopListening(mSelectedChannel);
			// mCamera.stopShow(mSelectedChannel);
			// }

			if (monitor != null) {
				monitor.deattachCamera();
			}

			Configuration cfg = getResources().getConfiguration();

			if (cfg.orientation == Configuration.ORIENTATION_PORTRAIT) {
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						setupViewInPortraitLayout_wait();
						// mCamera.startShow(mSelectedChannel, true, false);
						mCHTextView.setText("CH" + (mSelectedChannel + 1));
					}
				});
			} else if (cfg.orientation == Configuration.ORIENTATION_LANDSCAPE) {
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						setupViewInLandscapeLayout_wait();
						// mCamera.startShow(mSelectedChannel, true, false);
					}
				});
			}

			wait_receive = false;
		}
	}

	@Override
	public void receiveFrameInfo(final Camera camera, int avChannel,
			long bitRate, int frameRate, int onlineNm, int frameCount,
			int incompleteFrameCount) {

		if (mCamera == camera && avChannel == mSelectedChannel) {

			mVideoFPS = frameRate;
			mVideoBPS = bitRate;
			mOnlineNm = onlineNm;
			mFrameCount = frameCount;
			mIncompleteFrameCount = incompleteFrameCount;

			Bundle bundle = new Bundle();
			bundle.putInt("avChannel", avChannel);

			Message msg = handler.obtainMessage();
			msg.what = STS_CHANGE_CHANNEL_STREAMINFO;
			msg.setData(bundle);
			handler.sendMessage(msg);
		}
	}

	@Override
	public void receiveChannelInfo(final Camera camera, int avChannel,
			int resultCode) {

		if (mCamera == camera && avChannel == mSelectedChannel) {
			Bundle bundle = new Bundle();
			bundle.putInt("avChannel", avChannel);

			Message msg = handler.obtainMessage();
			msg.what = resultCode;
			msg.setData(bundle);
			handler.sendMessage(msg);
		}
	}

	@Override
	public void receiveSessionInfo(final Camera camera, int resultCode) {

		if (mCamera == camera) {
			Bundle bundle = new Bundle();
			Message msg = handler.obtainMessage();
			msg.what = resultCode;
			msg.setData(bundle);
			handler.sendMessage(msg);
		}
	}

	@Override
	public void receiveIOCtrlData(final Camera camera, int avChannel,
			int avIOCtrlMsgType, byte[] data) {

		if (mCamera == camera) {
			Bundle bundle = new Bundle();
			bundle.putInt("avChannel", avChannel);
			bundle.putByteArray("data", data);

			Message msg = handler.obtainMessage();
			msg.what = avIOCtrlMsgType;
			msg.setData(bundle);
			handler.sendMessage(msg);
		}
	}

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {

			Bundle bundle = msg.getData();
			int avChannel = bundle.getInt("avChannel");
			byte[] data = bundle.getByteArray("data");

			St_SInfo stSInfo = new St_SInfo();
			IOTCAPIs.IOTC_Session_Check(mCamera.getMSID(), stSInfo);

			switch (msg.what) {
			case AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GET_IMAGE_PARAM_RESP:
				Glog.I("bb", "-------------IOTYPE_BRIGHT_GETBRIGHT_RESP:"
						+ data[4]);

				mBrightness_Level = data[4];
				canSetBrightness = true;
				mVerSeekBar_Brightness.setEnabled(true);
				mVerSeekBar_Brightness.setProgress(mBrightness_Level);

				mContrast_Level = data[12];
				canSetContrast = true;
				seekbar_Contrast.setEnabled(true);
				seekbar_Contrast.setProgress(mContrast_Level);

				break;
			// case com.tutk.IOTC.AVIOCTRLDEFs.IOTYPE_BRIGHT_SETBRIGHT_RESP:
			// byte[] result = new byte[4];
			// System.arraycopy(data, 0, result, 0, 4);
			// ByteArrayInputStream bintput = new ByteArrayInputStream(result);
			// DataInputStream dintput = new DataInputStream(bintput);
			// try {
			// int i = dintput.readInt();
			// if (i == 0) {
			// Glog.I("bb",
			// "--------------------------IOTYPE_BRIGHT_SETBRIGHT_RESP------success!");
			// } else {// 恢复状态
			// Toast.makeText(LiveViewActivity.this,
			// R.string.tip_SetBright_Error,
			// Toast.LENGTH_SHORT).show();
			// mBrightness_Level = mPreBrightness_Level;
			// mVerSeekBar_Brightness.setProgress(mBrightness_Level);
			// }
			// } catch (IOException e) {
			// // TODO Auto-generated catch block
			// e.printStackTrace();
			// }
			//
			// break;
			case STS_CHANGE_CHANNEL_STREAMINFO:

				if (txtResolution != null) {
					if (mVideoWidth > 0 && mVideoHeight > 0) {
						txtResolution.setText(String.valueOf(mVideoWidth) + "x"
								+ String.valueOf(mVideoHeight));
					}
				}

				if (txtFrameRate != null)
					txtFrameRate.setText(String.valueOf(mVideoFPS));

				if (txtBitRate != null)
					txtBitRate.setText(String.valueOf(mVideoBPS) + "Kbps");

				if (txtOnlineNumber != null)
					txtOnlineNumber.setText(String.valueOf(mOnlineNm));

				if (txtFrameCount != null)
					txtFrameCount.setText(String.valueOf(mFrameCount));

				if (txtIncompleteFrameCount != null)
					txtIncompleteFrameCount.setText(String
							.valueOf(mIncompleteFrameCount));

				if (txtConnectionMode != null)
					txtConnectionMode
							.setText(getSessionMode(mCamera != null ? mCamera
									.getSessionMode() : -1)
									+ " C: "
									+ IOTCAPIs.IOTC_Get_Nat_Type()
									+ ", D: "
									+ stSInfo.NatType
									+ ",R"
									+ mCamera.getbResend());

				if (txtRecvFrmPreSec != null)
					txtRecvFrmPreSec.setText(String.valueOf(mCamera
							.getRecvFrmPreSec()));

				if (txtDispFrmPreSeco != null)
					txtDispFrmPreSeco.setText(String.valueOf(mCamera
							.getDispFrmPreSec()));

				if (txtPerformance != null)
					txtPerformance
							.setText(getPerformance((int) (((float) mCamera
									.getDispFrmPreSec() / (float) mCamera
									.getRecvFrmPreSec()) * 100)));

				break;

			case STS_SNAPSHOT_SCANED:

				Toast.makeText(LiveViewActivity.this,
						getText(R.string.tips_snapshot_ok), Toast.LENGTH_SHORT)
						.show();

				break;

			case Camera.CONNECTION_STATE_CONNECTING:

				if (!mCamera.isSessionConnected()
						|| !mCamera.isChannelConnected(mSelectedChannel)) {

					mConnStatus = getText(R.string.connstus_connecting)
							.toString();

					if (txtConnectionStatus != null) {
						txtConnectionStatus.setText(mConnStatus);
						txtConnectionStatus
								.setBackgroundResource(R.drawable.live_unknow);

					}
				}

				break;

			case Camera.CONNECTION_STATE_CONNECTED:

				if (mCamera.isSessionConnected()
						&& avChannel == mSelectedChannel
						&& mCamera.isChannelConnected(mSelectedChannel)) {

					mConnStatus = getText(R.string.connstus_connected)
							.toString();

					if (txtConnectionStatus != null) {
						txtConnectionStatus.setText(mConnStatus);
						txtConnectionStatus
								.setBackgroundResource(R.drawable.live_online);
					}

					LiveViewActivity.this.invalidateOptionsMenu();
				}

				break;

			case Camera.CONNECTION_STATE_DISCONNECTED:

				mConnStatus = getText(R.string.connstus_disconnect).toString();

				if (txtConnectionStatus != null) {
					txtConnectionStatus.setText(mConnStatus);
					txtConnectionStatus
							.setBackgroundResource(R.drawable.live_offline);
				}

				LiveViewActivity.this.invalidateOptionsMenu();

				break;

			case Camera.CONNECTION_STATE_UNKNOWN_DEVICE:

				mConnStatus = getText(R.string.connstus_unknown_device)
						.toString();

				if (txtConnectionStatus != null) {
					txtConnectionStatus.setText(mConnStatus);
					txtConnectionStatus
							.setBackgroundResource(R.drawable.live_offline);
				}

				LiveViewActivity.this.invalidateOptionsMenu();

				break;

			case Camera.CONNECTION_STATE_TIMEOUT:

				if (mCamera != null) {

					mCamera.stopSpeaking(mSelectedChannel);
					mCamera.stopListening(mSelectedChannel);
					mCamera.stopShow(mSelectedChannel);
					mCamera.stop(mSelectedChannel);
					mCamera.disconnect();
					mCamera.connect(mDevUID);
					mCamera.start(Camera.DEFAULT_AV_CHANNEL,
							mDevice.View_Account, mDevice.View_Password);
					mCamera.startShow(mSelectedChannel, true, m_RunSoftDecode,
							m_RunSoftDecode2);

					mCamera.connect(mDevUID);
					mCamera.start(Camera.DEFAULT_AV_CHANNEL,
							mDevice.View_Account, mDevice.View_Password);
					mCamera.sendIOCtrl(
							Camera.DEFAULT_AV_CHANNEL,
							AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GETSUPPORTSTREAM_REQ,
							SMsgAVIoctrlGetSupportStreamReq.parseContent());
					mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
							AVIOCTRLDEFs.IOTYPE_USER_IPCAM_DEVINFO_REQ,
							AVIOCTRLDEFs.SMsgAVIoctrlDeviceInfoReq
									.parseContent());
					mCamera.sendIOCtrl(
							Camera.DEFAULT_AV_CHANNEL,
							AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GETAUDIOOUTFORMAT_REQ,
							AVIOCTRLDEFs.SMsgAVIoctrlGetAudioOutFormatReq
									.parseContent());
					mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
							AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GET_TIMEZONE_REQ,
							AVIOCTRLDEFs.SMsgAVIoctrlTimeZone.parseContent());
					if (mIsListening)
						mCamera.startListening(mSelectedChannel, mIsRecording);
				}

				break;

			case Camera.CONNECTION_STATE_CONNECT_FAILED:

				mConnStatus = getText(R.string.connstus_connection_failed)
						.toString();

				if (txtConnectionStatus != null) {
					txtConnectionStatus.setText(mConnStatus);
					txtConnectionStatus
							.setBackgroundResource(R.drawable.live_offline);
				}

				LiveViewActivity.this.invalidateOptionsMenu();

				break;

			case Camera.CONNECTION_STATE_WRONG_PASSWORD:

				mConnStatus = getText(R.string.connstus_wrong_password)
						.toString();

				if (txtConnectionStatus != null) {
					txtConnectionStatus.setText(mConnStatus);
					txtConnectionStatus
							.setBackgroundResource(R.drawable.live_offline);
				}

				break;

			case AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GETSUPPORTSTREAM_RESP:

				LiveViewActivity.this.invalidateOptionsMenu();

				break;
			case AVIOCTRLDEFs.IOTYPE_USER_IPCAM_GET_ENVIRONMENT_RESP:
				EnvironmentMode = data[4];
				setEMode(EnvironmentMode);
				/*
				 * if (envMode >= 0 && envMode <= 3) {
				 * spinEnvironmentMode.setSelection(envMode, true);
				 * spinEnvironmentMode.setEnabled(true); mEnvMode = envMode; }
				 */
				break;
			}
		}
	};

	@Override
	public View makeView() {
		TextView t = new TextView(this);
		return t;
	}

	@Override
	public void OnClick() {

		// TODO Auto-generated method stub
		if (mIsListening || isOpenLinQVGA || isOpenLinEmode) {
			return;
		}

		if (isShowToolBar) {
			isShowToolBar = false;
			if (toolbar_layout != null)
				toolbar_layout.setVisibility(View.GONE);
			if (toolbar_layout_head != null)
				toolbar_layout_head.setVisibility(View.GONE);
		} else {
			isShowToolBar = true;
			if (toolbar_layout != null)
				toolbar_layout.setVisibility(View.VISIBLE);
			if (toolbar_layout_head != null)
				toolbar_layout_head.setVisibility(View.VISIBLE);
		}
	}

	private void ResetPre(int i) {
		// btn_pre1.setImageDrawable(getResources().getDrawable(R.drawable.position_01));
		// btn_pre2.setImageDrawable(getResources().getDrawable(R.drawable.position_02));
		// btn_pre3.setImageDrawable(getResources().getDrawable(R.drawable.position_03));
		// btn_pre4.setImageDrawable(getResources().getDrawable(R.drawable.position_04));
		// if(i == 1)
		// {
		// btn_pre1.setImageDrawable(getResources().getDrawable(R.drawable.position_01_click));
		// }else if(i == 2)
		// {
		// btn_pre2.setImageDrawable(getResources().getDrawable(R.drawable.position_02_click));
		// }
		// else if(i == 3)
		// {
		// btn_pre3.setImageDrawable(getResources().getDrawable(R.drawable.position_03_click));
		// }
		// else if(i == 4)
		// {
		// btn_pre4.setImageDrawable(getResources().getDrawable(R.drawable.position_04_click));
		// }
		toolbar_layout.setVisibility(View.VISIBLE);
		toolbar_layout.setAnimation(AnimationUtil.moveToViewLocation());
		toolbar_layout2.setVisibility(View.GONE);
		toolbar_layout2.setAnimation(AnimationUtil.moveToViewBottom());
	}

	Runnable LongClickRunnable = new Runnable() {
		@Override
		public void run() {
			TextView tv_reminder = (TextView) findViewById(R.id.tv_reminder);
			tv_reminder.setText(getString(R.string.Pre_hint));
			handler.removeCallbacks(LongClickRunnable);
			btn_pre1.setOnTouchListener(null);
			btn_pre2.setOnTouchListener(null);
			btn_pre3.setOnTouchListener(null);
			btn_pre4.setOnTouchListener(null);
			// mPreBtnLongPress = true;
		}
	};

	Runnable PreTextReturnRunnable = new Runnable() {
		@Override
		public void run() {
			if (pre_text != null) {
				pre_text.setText(R.string.Pre_hint);
			}
		}
	};

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub

		switch (event.getAction()) {
		case MotionEvent.ACTION_UP: {
			switch (v.getId()) {
			case R.id.btn_pre1:
			case R.id.btn_pre2:
			case R.id.btn_pre3:
			case R.id.btn_pre4:
				// mPreBtnLongPress = false;
				handler.postDelayed(LongClickRunnable, 500);
				break;
			default:
				// if (mCamera != null) {
				// mCamera.startSpeaking(mSelectedChannel);
				// mCamera.stopListening(mSelectedChannel);
				// }
				break;
			}
			// break;
		}
		// case MotionEvent.ACTION_UP: {
		//
		// switch (v.getId()) {
		// case R.id.btn_pre1:
		// handler.removeCallbacks(LongClickRunnable);
		// if (!mPreBtnLongPress) {
		// mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
		// HICHIPIOCTRDEFs.IOTYPE_USER_IPCAM_GETPRESET_REQ,
		// HICHIPIOCTRDEFs.SMsgAVIoctrlGetPresetReq
		// .parseContent(Camera.DEFAULT_AV_CHANNEL, 1));
		// } else {
		// mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
		// HICHIPIOCTRDEFs.IOTYPE_USER_IPCAM_SETPRESET_REQ,
		// HICHIPIOCTRDEFs.SMsgAVIoctrlSetPresetReq
		// .parseContent(Camera.DEFAULT_AV_CHANNEL, 1));
		// }
		// // ResetPre(1);
		// break;
		// case R.id.btn_pre2:
		// handler.removeCallbacks(LongClickRunnable);
		// if (!mPreBtnLongPress) {
		// mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
		// HICHIPIOCTRDEFs.IOTYPE_USER_IPCAM_GETPRESET_REQ,
		// HICHIPIOCTRDEFs.SMsgAVIoctrlGetPresetReq
		// .parseContent(Camera.DEFAULT_AV_CHANNEL, 2));
		// } else {
		// mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
		// HICHIPIOCTRDEFs.IOTYPE_USER_IPCAM_SETPRESET_REQ,
		// HICHIPIOCTRDEFs.SMsgAVIoctrlSetPresetReq
		// .parseContent(Camera.DEFAULT_AV_CHANNEL, 2));
		// }
		// // ResetPre(2);
		// break;
		// case R.id.btn_pre3:
		// handler.removeCallbacks(LongClickRunnable);
		// if (!mPreBtnLongPress) {
		// mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
		// HICHIPIOCTRDEFs.IOTYPE_USER_IPCAM_GETPRESET_REQ,
		// HICHIPIOCTRDEFs.SMsgAVIoctrlGetPresetReq
		// .parseContent(Camera.DEFAULT_AV_CHANNEL, 3));
		// } else {
		// mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
		// HICHIPIOCTRDEFs.IOTYPE_USER_IPCAM_SETPRESET_REQ,
		// HICHIPIOCTRDEFs.SMsgAVIoctrlSetPresetReq
		// .parseContent(Camera.DEFAULT_AV_CHANNEL, 3));
		// }
		// // ResetPre(3);
		// break;
		// case R.id.btn_pre4:
		// handler.removeCallbacks(LongClickRunnable);
		// if (!mPreBtnLongPress) {
		// mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
		// HICHIPIOCTRDEFs.IOTYPE_USER_IPCAM_GETPRESET_REQ,
		// HICHIPIOCTRDEFs.SMsgAVIoctrlGetPresetReq
		// .parseContent(Camera.DEFAULT_AV_CHANNEL, 4));
		// } else {
		// mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
		// HICHIPIOCTRDEFs.IOTYPE_USER_IPCAM_SETPRESET_REQ,
		// HICHIPIOCTRDEFs.SMsgAVIoctrlSetPresetReq
		// .parseContent(Camera.DEFAULT_AV_CHANNEL, 4));
		// }
		// // ResetPre(4);
		// break;
		// default:
		// if (mCamera != null) {
		// mCamera.stopSpeaking(mSelectedChannel);
		// mCamera.startListening(mSelectedChannel, mIsRecording);
		// }
		// break;
		// }
		// break;
		// }
		}
		return false;
	}

	@Override
	public void OnSnapshotComplete() {
		// TODO Auto-generated method stub
		MediaScannerConnection.scanFile(LiveViewActivity.this,
				new String[] { mFilePath.toString() },
				new String[] { "image/*" },
				new MediaScannerConnection.OnScanCompletedListener() {
					public void onScanCompleted(String path, Uri uri) {
						Log.i("ExternalStorage", "Scanned " + path + ":");
						Log.i("ExternalStorage", "-> uri=" + uri);
						Message msg = handler.obtainMessage();
						msg.what = STS_SNAPSHOT_SCANED;
						handler.sendMessage(msg);
					}
				});
	}

	private void sendSetBrightCMD() {
		mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
				AVIOCTRLDEFs.IOTYPE_USER_IPCAM_SET_IMAGE_PARAM_REQ,
				HICHIPIOCTRDEFs.SMsgAVIoctrlSetImageParamReq.parseContent(
						Camera.DEFAULT_AV_CHANNEL, mBrightness_Level, 110,
						mContrast_Level, 0));
	}

	private void sendSetContrastCMD() {
		mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
				AVIOCTRLDEFs.IOTYPE_USER_IPCAM_SET_IMAGE_PARAM_REQ,
				HICHIPIOCTRDEFs.SMsgAVIoctrlSetImageParamReq.parseContent(
						Camera.DEFAULT_AV_CHANNEL, mBrightness_Level, 110,
						mContrast_Level, 0));
	}

	private boolean isFirsSetLoad = true; // 是第一次加载view
	private boolean isSecond = true;

	private class BrightnessOnSeekBarChangeListener implements
			VerticalSeekBar.OnSeekBarChangeListener {

		@Override
		public void onProgressChanged(SeekBar seekBar, int progress,
				boolean fromUser) {

			if (isFirsSetLoad) {
				isFirsSetLoad = false;

				return;
			}
			if (isSecond) {
				isSecond = false;
				return;
			}
			Log.i("bb", "第一次不执行啊!!!!!!!!！！！！！");
			mPreBrightness_Level = mBrightness_Level;
			mBrightness_Level = progress; //
			sendSetBrightCMD();
		}

		@Override
		public void onStartTrackingTouch(SeekBar seekBar) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onStopTrackingTouch(SeekBar seekBar) {
			// TODO Auto-generated method stub

		}

	}

	private class ContrastOnSeekBarChangeListener implements
			VerticalSeekBar.OnSeekBarChangeListener {

		@Override
		public void onProgressChanged(SeekBar seekBar, int progress,
				boolean fromUser) {

			if (isFirsSetLoad) {
				isFirsSetLoad = false;
				return;
			}
			if (isSecond) {
				isSecond = false;
				return;
			}
			Log.i("bb", "第一次不执行啊!!!!!!!!！！！！！");
			mPreContrast_Level = mContrast_Level;
			mContrast_Level = progress; //
			sendSetContrastCMD();
		}

		@Override
		public void onStartTrackingTouch(SeekBar seekBar) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onStopTrackingTouch(SeekBar seekBar) {
			// TODO Auto-generated method stub

		}

	}

	private long getAvailaleSize() {

		File path = Environment.getExternalStorageDirectory();
		StatFs stat = new StatFs(path.getPath());
		long blockSize = stat.getBlockSize();
		long availableBlocks = stat.getAvailableBlocks();

		return (availableBlocks * blockSize) / 1024 / 1024;
	}

	@Override
	public void receiveFrameDataForMediaCodec(Camera arg0, int arg1,
			byte[] arg2, int arg3, int arg4, byte[] arg5, boolean arg6, int arg7) {
		// TODO Auto-generated method stub
		/*
		 * public void receiveFrameDataForMediaCodec(Camera camera, int
		 * avChannel, byte[] buf, int length, int pFrmNo, byte[] pFrmInfoBuf,
		 * boolean isIframe) {
		 */
		// TODO Auto-generated method stub

		if (monitor != null
				&& monitor.getClass().equals(MediaCodecMonitor.class)) {
			mVideoWidth = ((MediaCodecMonitor) monitor).getVideoWidth();
			mVideoHeight = ((MediaCodecMonitor) monitor).getVideoHeight();
		}

		if (wait_receive) {

			if (monitor != null) {
				monitor.deattachCamera();
			}

			Configuration cfg = getResources().getConfiguration();

			if (cfg.orientation == Configuration.ORIENTATION_PORTRAIT) {
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						setupViewInPortraitLayout_wait_Mediacodec();
						// mCamera.startShow(mSelectedChannel, true, false);
						mCHTextView.setText("CH" + (mSelectedChannel + 1));
					}
				});
			} else if (cfg.orientation == Configuration.ORIENTATION_LANDSCAPE) {
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						setupViewInLandscapeLayout_wait_Mediacodec();
						// mCamera.startShow(mSelectedChannel, true, false);
					}
				});
			}

			wait_receive = false;
		}
	}

	@Override
	public void Unavailable() {
		unavailable = true;

		if (monitor != null) {
			monitor.deattachCamera();
		}

		Configuration cfg = getResources().getConfiguration();

		if (cfg.orientation == Configuration.ORIENTATION_PORTRAIT) {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					setupViewInPortraitLayout_wait();
					mCHTextView.setText("CH" + (mSelectedChannel + 1));
				}
			});
		} else if (cfg.orientation == Configuration.ORIENTATION_LANDSCAPE) {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					setupViewInLandscapeLayout_wait();
				}
			});
		}
	}

	@Override
	public void zoomSurface(float scale) {

		SurfaceView surfaceView = (SurfaceView) monitor;
		android.view.ViewGroup.LayoutParams lp = surfaceView.getLayoutParams();

		lp.width = (int) (mMiniVideoWidth * scale);
		lp.height = (int) (mMiniVideoHeight * scale);

		surfaceView.setLayoutParams(lp);
	}

	private static byte[] setZoomParam(byte control) {
		byte[] result = new byte[8];

		result[0] = control;

		// byte[] rb = Packet.intToByteArray_Little(10);
		if (control == 23) {
			result[1] = (byte) 10;
			result[7] = 10;
		}
		if (control == 24) {
			result[1] = (byte) 10;
			result[7] = 10;
		}

		/*
		 * byte[] size = Packet.intToByteArray_Little(???);
		 * System.arraycopy(size, 0, result, 0, 4);
		 * 
		 * byte[] isSupportTimeZone =
		 * Packet.intToByteArray_Little(nIsSupportTimeZone);
		 * System.arraycopy(isSupportTimeZone, 0, result, 4, 4);
		 * 
		 * byte[] GMTDiff = Packet.intToByteArray_Little(nGMTDiff);
		 * System.arraycopy(GMTDiff, 0, result, 8, 4);
		 * 
		 * System.arraycopy(szTimeZoneString, 0, result, 12,
		 * szTimeZoneString.length);
		 */

		return result;
	}

	private void SetPTZ(byte cmd) {
		mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
				AVIOCTRLDEFs.IOTYPE_USER_IPCAM_PTZ_COMMAND, setZoomParam(cmd));
	}

	public void onZoomAdd(View v) {// AVIOCTRL_LENS_ZOOM_IN = 23,
		SetPTZ((byte) 23);
	}

	public void onZoomSub(View v) {// AVIOCTRL_LENS_ZOOM_OUT = 24,
		SetPTZ((byte) 24);
	}

	public void onPTZ_UP(View v) {// AVIOCTRL_PTZ_UP = 1,
		SetPTZ((byte) 1);
	}

	public void onPTZ_DOWN(View v) {// AVIOCTRL_PTZ_DOWN = 2,
		SetPTZ((byte) 2);
	}

	public void onPTZ_RIGHT(View v) {// AVIOCTRL_PTZ_RIGHT = 6,
		SetPTZ((byte) 6);
	}

	public void onPTZ_LEFT(View v) {// AVIOCTRL_PTZ_LEFT = 3,
		SetPTZ((byte) 3);
	}

	public void onPTZ_Back(View v) {// AVIOCTRL_PTZ_LEFT = 3,
		finish();
	}

	private Runnable zoom_runable = new Runnable() {
		@Override
		public void run() {
			if (ZoomAction == EMZoomAction.zoom_in) {
				Log.i("AAA", "ACTION_DOWN:mActionDown_IN=");
				SetPTZ((byte) 23);
				// handler.postDelayed(zoom_runable, mZoomOperDelayIn);
			} else {
				Log.i("AAA", "ACTION_DOWN:mActionDown_OUT=");
				SetPTZ((byte) 24);
				// handler.postDelayed(zoom_runable, mZoomOperDelayOut);
			}

		}
	};
	OnTouchListener touch = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN: {
				switch (v.getId()) {
				case R.id.btn_pre1:
				case R.id.btn_pre2:
				case R.id.btn_pre3:
				case R.id.btn_pre4:
					mPreBtnLongPress = false;
					handler.postDelayed(LongClickRunnable, 3000);
					break;
				default:
					if (mCamera != null) {
						mCamera.startSpeaking(mSelectedChannel);
						mCamera.stopListening(mSelectedChannel);
					}
					break;
				}
				break;
			}
			case MotionEvent.ACTION_UP: {
				switch (v.getId()) {
				case R.id.btn_pre1:
					handler.removeCallbacks(LongClickRunnable);
					if (!mPreBtnLongPress) {
						mCamera.sendIOCtrl(
								Camera.DEFAULT_AV_CHANNEL,
								HICHIPIOCTRDEFs.IOTYPE_USER_IPCAM_GETPRESET_REQ,
								HICHIPIOCTRDEFs.SMsgAVIoctrlGetPresetReq
										.parseContent(
												Camera.DEFAULT_AV_CHANNEL, 1));
					} else {
						mCamera.sendIOCtrl(
								Camera.DEFAULT_AV_CHANNEL,
								HICHIPIOCTRDEFs.IOTYPE_USER_IPCAM_SETPRESET_REQ,
								HICHIPIOCTRDEFs.SMsgAVIoctrlSetPresetReq
										.parseContent(
												Camera.DEFAULT_AV_CHANNEL, 1));
					}
					break;
				case R.id.btn_pre2:
					handler.removeCallbacks(LongClickRunnable);
					if (!mPreBtnLongPress) {
						mCamera.sendIOCtrl(
								Camera.DEFAULT_AV_CHANNEL,
								HICHIPIOCTRDEFs.IOTYPE_USER_IPCAM_GETPRESET_REQ,
								HICHIPIOCTRDEFs.SMsgAVIoctrlGetPresetReq
										.parseContent(
												Camera.DEFAULT_AV_CHANNEL, 2));
					} else {
						mCamera.sendIOCtrl(
								Camera.DEFAULT_AV_CHANNEL,
								HICHIPIOCTRDEFs.IOTYPE_USER_IPCAM_SETPRESET_REQ,
								HICHIPIOCTRDEFs.SMsgAVIoctrlSetPresetReq
										.parseContent(
												Camera.DEFAULT_AV_CHANNEL, 2));
					}
					break;
				case R.id.btn_pre3:
					handler.removeCallbacks(LongClickRunnable);
					if (!mPreBtnLongPress) {
						mCamera.sendIOCtrl(
								Camera.DEFAULT_AV_CHANNEL,
								HICHIPIOCTRDEFs.IOTYPE_USER_IPCAM_GETPRESET_REQ,
								HICHIPIOCTRDEFs.SMsgAVIoctrlGetPresetReq
										.parseContent(
												Camera.DEFAULT_AV_CHANNEL, 3));
					} else {
						mCamera.sendIOCtrl(
								Camera.DEFAULT_AV_CHANNEL,
								HICHIPIOCTRDEFs.IOTYPE_USER_IPCAM_SETPRESET_REQ,
								HICHIPIOCTRDEFs.SMsgAVIoctrlSetPresetReq
										.parseContent(
												Camera.DEFAULT_AV_CHANNEL, 3));
					}
					break;
				case R.id.btn_pre4:
					handler.removeCallbacks(LongClickRunnable);
					if (!mPreBtnLongPress) {
						mCamera.sendIOCtrl(
								Camera.DEFAULT_AV_CHANNEL,
								HICHIPIOCTRDEFs.IOTYPE_USER_IPCAM_GETPRESET_REQ,
								HICHIPIOCTRDEFs.SMsgAVIoctrlGetPresetReq
										.parseContent(
												Camera.DEFAULT_AV_CHANNEL, 4));
					} else {
						mCamera.sendIOCtrl(
								Camera.DEFAULT_AV_CHANNEL,
								HICHIPIOCTRDEFs.IOTYPE_USER_IPCAM_SETPRESET_REQ,
								HICHIPIOCTRDEFs.SMsgAVIoctrlSetPresetReq
										.parseContent(
												Camera.DEFAULT_AV_CHANNEL, 4));
					}
					break;
				default:
					if (mCamera != null) {
						mCamera.stopSpeaking(mSelectedChannel);
						mCamera.startListening(mSelectedChannel, mIsRecording);
					}
					break;
				}
				break;
			}
			}
			return false;
		}
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.button_brightness:
			seekbar_Contrast.setVisibility(View.GONE);
			if (mVerSeekBar_Brightness.getVisibility() == 8) {
				mVerSeekBar_Brightness.setVisibility(View.VISIBLE);
			} else {
				mVerSeekBar_Brightness.setVisibility(View.GONE);
			}

			break;
		case R.id.button_contrast:
			mVerSeekBar_Brightness.setVisibility(View.GONE);
			if (seekbar_Contrast.getVisibility() == 8) {
				seekbar_Contrast.setVisibility(View.VISIBLE);
			} else {
				seekbar_Contrast.setVisibility(View.GONE);
			}
			break;
		case R.id.btn_restore:
			mCamera.sendIOCtrl(Camera.DEFAULT_AV_CHANNEL,
					AVIOCTRLDEFs.IOTYPE_USER_IPCAM_SET_IMAGE_PARAM_REQ,
					HICHIPIOCTRDEFs.SMsgAVIoctrlSetImageParamReq.parseContent(
							Camera.DEFAULT_AV_CHANNEL, 50, 55, 50, 50));
			mVerSeekBar_Brightness.setProgress(50);
			seekbar_Contrast.setProgress(55);
			break;
		default:
			break;
		}

	}
}
